C#:如何在 Socket.BeginReceive 回调之前终止套接字?

C#: How do I terminate a socket before Socket.BeginReceive calls back?(C#:如何在 Socket.BeginReceive 回调之前终止套接字?)

本文介绍了C#:如何在 Socket.BeginReceive 回调之前终止套接字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从客户端接收连接请求的服务器.该服务器使用异步 Socket.BeginReceiveSocket.EndReceive 方法.该代码与此处的代码非常相似.

I have a server that receives connection requests from clients. This server makes use of the asynchronous Socket.BeginReceive and Socket.EndReceive method. The code is pretty similar to the code found here.

在我的情况下,在调用 Socket.BeginReceive 之后,我需要一个超时,这样如果客户端挂在连接上但在固定的时间内根本没有传输任何数据,我需要终止连接.

In my case, after calling Socket.BeginReceive I need a timeout such that if the client hangs on to the connection but does not transmit any data at all for a fixed amount of time, I need to terminate the connection.

  • 如何终止在这种情况下连接?
  • 编写代码的最佳方法是什么计时器?

推荐答案

只需调用socket的Close()方法即可.之后回调方法将很快运行,当您调用 EndReceive() 方法时,您将得到一个 ObjectDisposedException.准备好捕获该异常.

Just call the socket's Close() method. The callback method will run pretty quickly after that, you'll get an ObjectDisposedException when you call the EndReceive() method. Be prepared to catch that exception.

您可能不想阻塞调用 BeginReceive 的线程,您需要一个 System.Threading.TimerSystem.Timers.Timer 来检测超时.它的回调应该调用Close().请注意这导致的不可避免的竞争条件,如果在计时器到期前一微秒收到响应,则计时器的回调将运行.即使您得到了很好的响应,您也会关闭套接字.对 BeginReceive() 的下一次调用将立即失败.

You probably don't want to block the thread that called BeginReceive, you'll need a System.Threading.Timer or System.Timers.Timer to detect the timeout. Its callback should call Close(). Beware of the inevitable race-condition this causes, the timer's callback will run if the response was received a microsecond before the timer expired. You'll close the socket, even though you got a good response. The next call to BeginReceive() will fail immediately.

这篇关于C#:如何在 Socket.BeginReceive 回调之前终止套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C#:如何在 Socket.BeginReceive 回调之前终止套接字?

基础教程推荐