C# UdpClient beginreceive如何检测服务器何时关闭
我有一个应用程序,它正在32个不同端口上从Udp服务器读取数据,我需要处理这些端口。我正在使用UdpClient.BeginReceive调用它自己,因为我想一直听:C# UdpClient beginreceive如何检测服务器何时关闭,c#,sockets,udpclient,C#,Sockets,Udpclient,我有一个应用程序,它正在32个不同端口上从Udp服务器读取数据,我需要处理这些端口。我正在使用UdpClient.BeginReceive调用它自己,因为我想一直听: private void ProcessEndpointData(IAsyncResult result) { UdpClient client = result.AsyncState as UdpClient; // points towards whoever had sent th
private void ProcessEndpointData(IAsyncResult result)
{
UdpClient client = result.AsyncState as UdpClient;
// points towards whoever had sent the message:
IPEndPoint source = new IPEndPoint(0, 0);
// schedule the next receive operation once reading is done:
client.BeginReceive(new AsyncCallback(this.ProcessEndpointData), client);
// get the actual message and fill out the source:
this.DecodeDatagram(new DatagrammeAscb()
{
Datagramme = this.ByteArrayToStructure<Datagram>(client.EndReceive(result, ref source))
});
}
private void ProcessEndpointData(IAsyncResult结果)
{
UdpClient client=result.AsyncState作为UdpClient;
//指向发送消息的人:
IPEndPoint源=新IPEndPoint(0,0);
//读取完成后,安排下一个接收操作:
client.BeginReceive(新的AsyncCallback(this.ProcessEndpointData),client);
//获取实际消息并填写来源:
this.DecodeDatagram(新数据语法ascb()
{
Datagramme=this.ByteArrayToStructure(client.EndReceive(result,ref-source))
});
}
当我停止服务器端时,函数正在等待数据(这是正常行为)。我想做的是检测服务器何时断开连接,然后关闭所有客户端
我在问自己是否应该使用sockets类来拥有更多的控件,或者只是我在这里遗漏了一些东西
无论如何,谢谢你的帮助。UDP的关键在于它不在乎另一端是否有什么东西。你可以发送一个毒药包。UDP本身不会给你这个。顺便说一句,TCP都不是。就个人而言,我会在几个层面上做这件事:1。发送毒药包(通知客户端,服务器正在关闭)。不仅发送一个,而且发送多个(UDP不可靠)。2.有一些超时和“你在吗”功能。因此,如果在x个时间段内没有与服务器的com,则发送某种类型的ping,如果在合理的时间内没有答案,则假设服务器已关闭。问题是我不处理服务器端(代码),并且我无法更改任何内容。如果可能的话,我希望不花一点时间来处理超时,因为我正在努力提高效率,特别是在CPU方面。谢谢你的提示。