(Socket.SendTo)如何响应/发送回我的服务器开始接收的客户端的数据? C#
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了(Socket.SendTo)如何响应/发送回我的服务器开始接收的客户端的数据? C#相关的知识,希望对你有一定的参考价值。
我正在做一个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);
}
答案
我弄清楚该怎么做。我将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);
}
以上是关于(Socket.SendTo)如何响应/发送回我的服务器开始接收的客户端的数据? C#的主要内容,如果未能解决你的问题,请参考以下文章
使用 Datatable.js 时,如何将我点击的页面编号发送回我的后端? (有一些小问题)
使用 AngularJS、WebAPI 2 和 Oauth 2 时,如何将授权信息发送回我的客户端应用程序?