UDP Client 在伺服器端只會有一個instance,Server 與 Client 須先進行 TCP 的連線,成功連線後伺服器會回傳 Client ID給玩家,玩家須將此 ID 寫入 UDP 請求連線的封包中,在伺服器端會根據此 ID 的 IPEndPoint 來建立UDP 連線。
public static void Start(int _maxPlayers, int _port)
{
//原TCP Code
udpListener = new UdpClient(Port);
udpListener.BeginReceive(UDPReceiveCallback, null);
}
public class UDP
{
public UdpClient socket;
public IPEndPoint endPoint;
public UDP()
{
endPoint = new IPEndPoint(IPAddress.Parse(instance.ip), instance.port);
}
/// <summary>Attempts to connect to the server via UDP.</summary>
/// <param name="_localPort">The port number to bind the UDP socket to.</param>
public void Connect(int _localPort)
{
socket = new UdpClient(_localPort);
socket.Connect(endPoint);
socket.BeginReceive(ReceiveCallback, null);
using (Packet _packet = new Packet())
{
SendData(_packet);
}
}
}