我需要与2名玩家进行客户端 - 服务器游戏。我绑定localhost和不同端口上的客户端套接字。对于连接客户端,使用枚举标头发送序列化消息,并将IPEndPoints作为值发送。当服务器从不同的客户端接收连接消息时,它们具有相同的端口。如何解决?
接收连接的方法:
public static void GetConnections()
{
while (true)
{
Console.WriteLine("Waiting for connections...");
var len = ServerSocket.Receive(TempData);
var msg = (NetMessage)DataSerializer.Deserialize(TempData);
Console.WriteLine(msg.Data.ToString());
if (msg.PacketType == PacketType.CONNECT)
{
String[] IP = msg.Data.ToString().Split(':');
if (Player1IP == null)
{
Player1IP = new IPEndPoint(IPAddress.Parse(IP[0]), Int32.Parse(IP[1]));
Console.WriteLine("Approved connection of player 1 with remote endpoint: " + Player1IP);
}
else if (Player2IP == null)
{
Player2IP = new IPEndPoint(IPAddress.Parse(IP[0]), Int32.Parse(IP[1]));
Console.WriteLine("Approved connection of player 2 with remote endpoint: " + Player2IP);
}
if (Player1IP != null && Player2IP != null)
{
Console.WriteLine("Both player are connected");
Console.WriteLine(Player1IP + " " + Player2IP);
return;
}
}
}
连接方法(运行一次):
public void GetConnection()
{
NetMessage msg = new NetMessage(PacketType.CONNECT, ClientSocket.LocalEndPoint.ToString());
var bytes = DataSerializer.Serialize(msg);
ClientSocket.SendTo(bytes, ServerIP);
BeganConnection = true;
}