Я пытаюсь написать асинхронный сервер udp, и мне трудно понять, как работают некоторые вещи.В этом коде программа останавливается на методе ClientConnected (), говоря, что asyncResult.asyncstate в качестве сокета имеет значение null, так как я могу передать сокет отправителя обратному вызову?
class UDPServer
{
byte[] byteData;
int bufferSize;
public ManualResetEvent allDone = new ManualResetEvent(false);
Socket serverSocket;
IPEndPoint localIPEP;
EndPoint sender = new IPEndPoint(IPAddress.Any, 0);
IPEndPoint[,] playerList = new IPEndPoint[5000, 2]; // 5000 possible player lobbies, each with 2 player ip addresses and ports
int playerListIndex = 0; // we start filling up the lobbies from 0
bool waitingForSecondClient;
public UDPServer(IPEndPoint serverIpEndPoint)
{
bufferSize = 1024;
byteData = new byte[1024];
localIPEP = serverIpEndPoint;
serverSocket = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
serverSocket.Bind(localIPEP);
Console.WriteLine("Server setup complete.");
}
public void GetConnection()
{
while (true)
{
allDone.Reset();
Console.WriteLine("Waiting for new client.");
serverSocket.BeginReceiveFrom(byteData, 0, bufferSize, SocketFlags.None, ref sender, ClientConnected, sender);
allDone.WaitOne();
}
}
public void ClientConnected(IAsyncResult asyncResult)
{
allDone.Set();
byte[] data = new byte[1024];
data = byteData;
byteData = null;
Socket clientSocket = asyncResult.AsyncState as Socket;
EndPoint remote = clientSocket.LocalEndPoint;
int bytesReceived = serverSocket.EndReceiveFrom(asyncResult, ref remote);
string message = Encoding.ASCII.GetString(data, 0, bytesReceived);
remote = new IPEndPoint(IPAddress.Any, 0);
serverSocket.BeginReceiveFrom(byteData, 0, bufferSize, SocketFlags.None, ref remote, ClientConnected, remote);
Console.WriteLine("-------------");
Console.WriteLine("Received bytes of data: " + bytesReceived);
Console.WriteLine("-------------");
Console.WriteLine("Received string: " + message);
Console.WriteLine("-------------");
if (message.Equals("New client"))
{
Send(clientSocket, "Hello");
}