Я новичок в кодировании, особенно в async, и впервые пытаюсь реализовать его на сервере udp для игры, над которой я работаю (1 на 1).На синхронном сервере udp код останавливается, когда мы делаем receivefrom, так как я могу сделать то же самое в async?В настоящее время консоль проходит через метод GetConnection () и просто закрывается вместо ожидания клиента.Помогите пожалуйста.
// State object for reading client data asynchronously
public class StateObject
{
// Client socket.
public Socket clientSocket = null;
// Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
class UDPServer
{
Socket serverSocket;
IPEndPoint localIPEP;
IPEndPoint senderIPEP;
EndPoint sender;
IPEndPoint[,] playerList;
int playerListIndex;
bool waitingForSecondClient;
public UDPServer(IPEndPoint serverIpEndPoint)
{
localIPEP = serverIpEndPoint;
serverSocket = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
serverSocket.Bind(localIPEP);
senderIPEP = new IPEndPoint(IPAddress.Any, 0);
sender = senderIPEP;
playerList = new IPEndPoint[5000, 2]; // 5000 possible player lobbies, each with 2 player ip addresses and ports
playerListIndex = 0; // we start filling up the lobbies from 0
Console.WriteLine("Server setup complete.");
}
public void GetConnection()
{
StateObject state = new StateObject();
Console.WriteLine("Waiting for new client.");
serverSocket.BeginReceiveFrom(state.buffer, 0, StateObject.BufferSize, SocketFlags.None,ref sender, ClientConnected, state);
}
public void ClientConnected(IAsyncResult asyncResult)
{
StateObject state = (StateObject)asyncResult;
EndPoint remote = state.clientSocket.LocalEndPoint;
StateObject tempState = new StateObject();
int bytesReceived = serverSocket.EndReceiveFrom(asyncResult, ref remote);
serverSocket.BeginReceiveFrom(tempState.buffer, 0, StateObject.BufferSize, SocketFlags.None, ref remote, ClientConnected, tempState);
Console.WriteLine("-------------");
Console.WriteLine("Received bytes of data: " + bytesReceived);
Console.WriteLine("-------------");
Console.WriteLine("Received string: " + state.sb.ToString());
Console.WriteLine("-------------");
if (state.sb.ToString().Equals("New client"))
{
Send(state.clientSocket, "Hello");
}
}
private void Send(Socket client,string message)
{
EndPoint remote = client.LocalEndPoint;
StateObject state = new StateObject();
// Begin sending the data to the remote device.
serverSocket.BeginSendTo(state.buffer, 0, StateObject.BufferSize, 0,remote,SendCallback,state);
}
private static void SendCallback(IAsyncResult asyncResult)
{
// Retrieve the socket from the state object.
Socket client = (Socket)asyncResult.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = client.EndSendTo(asyncResult);
}
static void Main(string[] args)
{
UDPServer server = new UDPServer(new IPEndPoint(IPAddress.Any, 9050));
server.GetConnection();
}
}