我正在尝试编写一个异步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");
}