C#中:我如何终止插座Socket.BeginReceive回叫过吗? [英] C#: How do I terminate a socket before Socket.BeginReceive calls back?

查看:647
本文介绍了C#中:我如何终止插座Socket.BeginReceive回叫过吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接收来自客户端的连接请求的服务器。此服务器使用了异步 Socket.BeginReceive Socket.EndReceive 的方法。到代码中发现 rel=\"nofollow\">的代码非常相似。

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.


  • 我如何去终止此方案中的
    连接?

  • 什么是编写一个
    计时器?

推荐答案

只要打电话给套接字的关闭()方法。回调方法将运行以后很快,你会得到一个的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 来检测超时。它的回调应该叫关闭()。当心不可避免的竞争条件这将导致,如果响应收到一个微秒的计时器到期之前计时器的回调将运行。你会关闭套接字,即使你得到了良好的反响。到 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回叫过吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆