且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在UDP应用程序中关闭客户端或服务器时

更新时间:2023-02-20 19:25:07

我多年前在VB6中做过这个,但我记得如果他们无法联系机器名,就会抛出异常。但是,如果机器在线,但你的应用程序没有收听,那么我所做的就是实现一个轮询情况,所以如果我在一定时间内没有得到回复,那么它就会被假定为离线。您的另一个选择是使用TCP。
I did this many years ago in VB6 but as I recall an exception was thrown if they could not contact the machine name. However, if the machine is online but your app is not listening then what I did was implement a polling situation so if I did not get a response back in a certain amount of time it was assumed offline. Your other option is to use TCP.


这取决于使用的通信。



当对方定期发送数据包时,您可以在特定时间内没有收到数据时停止发送数据包,并在下次接收时继续发送。如果没有定期发送数据,只需发送它们即可。这种分组称为保活分组。如有必要,在程序启动时发送数据包以指示客户端/服务器存在并触发另一端开始发送。



使用上面的内容,你会发送数据包,直到发生超时。但这通常不是问题。如果您的通信协议可以更改,您可能会发送额外的特殊数据包,表明服务器或客户端正在关闭,以便另一方可以立即停止。
This depends on the used communication.

When the other side sends packets in regular intervals, you can stop sending packets when no data are received for a specific time and resume sending upon the next receive. If no data are send in regular intervals, just send them. Such packets are called keep-alive packets. If necessary, send a packet at program start to indicate that the client / server is present and trigger the other side to start sending.

Using the above, you will have packets send until the time out occurs. But this is normally not a problem. If your communication protocol can be changed, you might send additional special packets indicating that a server or client is going down so that the other side can stop immediately.


您可以设置自己的握手UDP之上的协议。换句话说,让接收方发送一个发送方将处理的响应。
You can set up your own handshake protocol on top of UDP. In other words, have the receiving machine send a response that the sender will process.