当网线与网络适配器断开时如何获取套接字的状态
我用C#编写了一个c/s模式的通信程序,服务器和客户端程序在不同的计算机上。今天,在客户端程序连接到服务器程序后,然后我从网络适配器上拔出电缆(此后,客户端和服务器程序没有执行任何操作),奇怪的事情发生了。我发现服务器程序的套接字仍然保持连接状态。我使用命令“netstat -a -n”来检索网络信息,并获取如下信息:
TCP 192.168.1.2:3645 192.168.1.3:1863 ESTABLISHED
192.168.1.2(服务器IP地址) 192.168.1.3(客户端IP地址)
有人知道原因吗?如何解决这个问题。 我想知道当客户端计算机的网线被拔出时,服务器程序如何接收事件并关闭套接字。
请给我一些建议或解决方案。
谢谢
I write a comunication program with c/s mode in C# ,server and client program on different computer. Today after client progarm connected to server progarm ,then I pulled out cable from network adapter (after this , client and server program didn't do anything), stranger thing happened. I found out socket of server program still keep connected status. and I use command "netstat -a -n" to retrieve network information ,and get information like following :
TCP 192.168.1.2:3645 192.168.1.3:1863 ESTABLISHED
192.168.1.2 (Server IP Address)
192.168.1.3 (Client IP Address)
Do anyone know the reason ? how to solve this problem .
I wanna how server program can receive the event and close the socket when network cable of client computer has been pulled out.
Please give me some advices or solutions.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为可以通过使用TCP keepalive来解决。
参考http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview。 html
连接后,设置套接字 keepalive 属性。 msdn说这个开关默认状态是关闭的,如果将keepalive设置为打开,socket会自动检查网络状态,第一次检查时间是在socket上次操作后2小时。但时间可以调短。然后在第一次检查后,套接字将 servral 次。如果连接断开或中断,
套接字将抛出异常。
C# 来源:
我查过了。运行正常啊
I think it can be solved by using TCP keepalive.
refrencehttp://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html
after connecting , set socket keepalive property . msdn say this switch default status is off , if set keepalive to on , socket will check the network status automaticly , and first check time is 2 hours after last operation on socket. but the time can be adjsut to short . then after first check , socket will servral times. if connection is down or died,
socket will throw exception .
C# Source:
I have checked. It's running ok.
你不能。
检查连接状态的唯一可靠方法是通过线路发送数据,因此: 处理发送/接收期间的连接失败,并且如果您想在空闲期间获取连接状态,也可以选择通过某种形式的 ping 定期检查连接状态。
You can't.
The only reliable way to check connected status is to send data over the wire, so: Deal with connection failures during send/receive, and, optionally, periodically check for connection status by some form of ping, if you want connection status during idle periods.
我有点不确定,但如果你在拔掉电缆后尝试从插座读取数据,它会告诉你它不再连接了。
Im a bit unsure but if you try to read data from the socket after you pulled the cable it will tell you that its not connected any more..