TCP套接字接收阻止方法 [英] TCP Socket receive blocking method

查看:88
本文介绍了TCP套接字接收阻止方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#中的"socket.Receive()"方法遇到了一些麻烦.这是一种等待接收数据的阻塞方法,但是在我的测试中,当套接字已连接并且如果连接断开(例如拔下电缆),它正在接收(阻塞)时,该方法仍将连接"到...好吧,我猜不到!它不会导致异常或其他任何情况.

为什么,这是怎么发生的?

I am having some trouble with the "socket.Receive()" method in C#. It is a blocking method that waits to receive data, but in my testings, when the socket is connected and it''s receiving (blocked) if the connection goes down (like, unplugging the cable) this method will be still "connected" to...well, nothing i guess! It does not cause an exception or anything else...

Why, how does this happens?

推荐答案

那是正确的.由于网络的性质和您使用的协议的原因,无法立即检测到此类中断.如果再等一会,您很可能会例外.如果您需要对网络中断的更快响应,请创建一些基于网络测试的自定义机制,例如根据您喜欢的超时进行ping操作.请参阅类System.Net.NetworkInformation.Ping http://msdn.microsoft.com/en -us/library/system.net.networkinformation.ping.aspx [ ^ ].

请记住,这将是一种乐观的机制,因此您需要注意可能出现的误报情况.因此您的代码应该能够处理它.

与网络相关的所有工作都涉及线程,即使您做的是基本的事情.
请参阅我过去关于网络线程设计的答案:
来自同一端口号的多个客户端 [如何获取keydown事件在vb.net中的不同线程上操作 [
That is correct. Due to the nature of networking and the protocols you use, such disruption can not be detected immediately. If you wait some more, you well get an exception. If you need faster response on network disruption, create some custom mechanism of network testing, base, for example of pinging with the timeout you prefer. See the class System.Net.NetworkInformation.Ping, http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping.aspx[^].

Remember, it would be optimistic mechanism, so you need to take care about possible false positives; so your code should be able to handle it.

All you do with networking involved threading, even if you do basic stuff.
Please see my past Answers on the networking threaded design:
Multple clients from same port Number[^].

This is my collection of references to my past Answers on threading:
How to get a keydown event to operate on a different thread in vb.net[^].

—SA


[像往常一样添加到SA的出色响应]

这是在S.O中针对此问题的一些替代建议.线程:

http://stackoverflow.com/questions/722240/instantly-detect-client-从服务器套接字断开连接 [ ^ ]
[Adding to SA''s as usual excellent response]

Here are some alternate suggestions to this problem in a S.O. thread:

http://stackoverflow.com/questions/722240/instantly-detect-client-disconnection-from-server-socket[^]


这篇关于TCP套接字接收阻止方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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