简体   繁体   English

套接字keepalive与XP一起使用,但不适用于Windows 7 C#

[英]socket keepalive works with xp but not with windows 7 c#

I have a strange problem: I have a list of TcpClients that I need to be notified when one of them disconnects. 我有一个奇怪的问题:我有一个TcpClients列表,其中一个断开连接时需要通知我。 When each of them is initialized I set their socket to keepalive (setsocketoption, and iocontrol) and there does not seem to be any problem with it (no exceptions). 当它们每个都初始化后,我将其套接字设置为keepalive(setsocketoption和iocontrol),并且似乎没有任何问题(无例外)。

Than I have a seperated thread that checks each TcpClient the Connected property of their Socket. 比我有一个单独的线程,它检查每个TcpClient的Socket的Connected属性。 The problem is that even when the ip is no longer connected (for example I disconnect the network cable) the boolean is still true (connected). 问题在于,即使不再连接ip(例如,我断开网络电缆的连接),布尔值仍然是true(已连接)。 I tried changing the code to (socket.available == true) && socket.poll(1, socketMode.selectread) without any change. 我尝试将代码更改为(socket.available == true)&& socket.poll(1,socketMode.selectread)保持不变。

A very important remark: The same exact code works with win Xp (the Connected property is false when there is no connection) but does not work with win7 and there are no exceptions. 一个非常重要的说明:Win Xp可以使用完全相同的代码(没有连接时,Connected属性为false),但不适用于win7,也没有例外。

I am running the program as administrator and I disabled the firewall. 我以管理员身份运行程序,并且禁用了防火墙。

Thank you in advance. 先感谢您。

The Connected boolean is true until either a Send or Receive operation fails. 直到“发送”或“接收”操作失败之前,“ Connected布尔”为true。 This is the nature of TCP/IP. 这就是TCP / IP的本质。 So for example if you had a connected socket from computer A to B, then unplugged the network cable on computer B, computer A wouldn't report the socket is disconnected until the next time you try to send some data. 因此,例如,如果您有一个从计算机A到B的连接插座,然后拔下了计算机B上的网络电缆,则计算机A不会报告该套接字已断开连接,直到您下次尝试发送一些数据为止。

I suggest implementing some kind of ping/pong mechanism that you send every n interval such as 5 seconds to see if the other end is still alive or not. 我建议实施某种ping / pong机制,您每隔n个间隔(例如5秒)发送一次,以查看另一端是否仍然存在。

I don't know why your tests show it's different on XP and windows 7, I would have thought there is no difference. 我不知道为什么您的测试表明在XP和Windows 7上它有所不同,我会认为没有区别。 Perhaps by chance on XP you were sending some data just after you unplugged the cable which triggered Connected to be set to false? 也许是偶然的机会,在XP上,拔下触发Connected设置为false的电缆后,您正在发送一些数据?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM