我正在使用UDP服务器,可以很好地接收数据,但是我不知道如何存储端点以将数据发送回去。
在SetupServer()
的最后一行的注释中,我不知道如何获得EndPoint
。
这是我的服务器代码:
static private byte[] buffer = new byte[1024];
static private Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
private const int port = 904;
static void Main(string[] args) {
SetupServer();
Console.ReadLine();
}
static private void SetupServer() {
Console.WriteLine($"{DateTime.Now}: Setting up server on {port}...");
EndPoint remoteEP = new IPEndPoint(IPAddress.Any, port);
serverSocket.Bind(remoteEP);
Console.WriteLine($"{DateTime.Now}: Server created successfully");
serverSocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref remoteEP,BeginReceive, null);
//serverSocket.SendTo(buffer, 0, buffer.Length, SocketFlags.None, remoteEP);
}
static private void BeginReceive(IAsyncResult ar) {
int recv = serverSocket.EndReceive(ar);
byte[] dataBuf = new byte[recv];
Array.Copy(buffer, dataBuf, recv);
Console.WriteLine($"{DateTime.Now}: {Encoding.ASCII.GetString(dataBuf)}");
EndPoint remoteEP = new IPEndPoint(IPAddress.Any, port);
serverSocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref remoteEP, BeginReceive, null);
}
答案 0 :(得分:0)
我知道该怎么做。我将serverSocket.EndReceive(ar)
方法中的BeginReceive
替换为EndReceiveFrom(ar,ref epSender)
,并使用端点(epSender)可以调用BeginReceiveFrom
方法。
static private void SetupServer() {
Console.WriteLine($"{DateTime.Now}: Setting up server on {port}...");
EndPoint remoteEP = new IPEndPoint(IPAddress.Any, port);
serverSocket.Bind(remoteEP);
Console.WriteLine($"{DateTime.Now}: Server created successfully");
serverSocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref remoteEP,BeginReceive, serverSocket);
}
static private void BeginReceive(IAsyncResult ar) {
EndPoint epSender = new IPEndPoint(IPAddress.Any, port);
int recv = serverSocket.EndReceiveFrom(ar,epSender);
byte[] dataBuf = new byte[recv];
Array.Copy(buffer, dataBuf, recv);
Console.WriteLine($"{DateTime.Now}: {Encoding.ASCII.GetString(dataBuf)}");
serverSocket.SendTo(dataBuf,epSender)
serverSocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref remoteEP, BeginReceive, serverSocket);
}