BeginReceive回调之前终止套接字

BeginReceive回调之前终止套接字

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

问题描述

我有一个服务器从客户端接收连接请求。此服务器使用异步 Socket.BeginReceive Socket.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.


  • 如何在这种情况下终止
    连接?


  • 计时器的最佳编码方式是什么?

推荐答案

只需调用套接字的 Close()方法。回调方法将很快运行后,你会得到一个 ObjectDisposedException 当你调用 EndReceive()方法。准备捕获异常。

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.Timer System.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回调之前终止套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 05:21