启用 DTLS 加密
注意:启用 DTLS 加密后,仅消息加密会启用,其他 Relay 行为(如超时)保持不变。
Relay 支持对 Relay 服务器传入/传出的所有 UDP 通信进行 DTLS 加密。当以主机玩家身份创建分配时,将 Relay 服务器 connectionType 设置为 dtls 即可启用 DTLS 加密。
警告:使用 DTLS 保护连接的功能仅在 Unity 编辑器版本 2020.3(从 2020.3.34 开始)、2022.1 以及更高版本中提供。
注意:加入玩家可以使用不同于主机玩家的连接类型,不过大部分游戏平台都要求加密连接。
以下代码片段中包含函数 AllocateRelayServerAndGetJoinCode,该函数展示了如何使用 Relay SDK 创建分配、请求加入代码以及将连接类型配置为 DTLS。
public static async Task<(string ipv4address, ushort port, byte[] allocationIdBytes, byte[] connectionData, byte[] key, string joinCode)> AllocateRelayServerAndGetJoinCode(int maxConnections, string region = null)
{
Allocation allocation;
string createJoinCode;
try
{
allocation = await RelayService.Instance.CreateAllocationAsync(maxConnections, region);
}
catch (Exception e)
{
Debug.LogError($"Relay create allocation request failed {e.Message}");
throw;
}
Debug.Log($"server connection data: {allocation.ConnectionData[0]} {allocation.ConnectionData[1]}");
Debug.Log($"server allocation ID: {allocation.AllocationId}");
try
{
createJoinCode = await RelayService.Instance.GetJoinCodeAsync(allocation.AllocationId);
}
catch
{
Debug.LogError("Relay create join code request failed");
throw;
}
var dtlsEndpoint = allocation.ServerEndpoints.First(e => e.ConnectionType == "dtls");
return (dtlsEndpoint.Host, (ushort)dtlsEndpoint.Port, allocation.AllocationIdBytes, allocation.ConnectionData, allocation.Key, createJoinCode);
}