简体   繁体   中英

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. 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).

Than I have a seperated thread that checks each TcpClient the Connected property of their Socket. 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). I tried changing the code to (socket.available == true) && socket.poll(1, socketMode.selectread) without any change.

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.

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. This is the nature of 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.

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.

I don't know why your tests show it's different on XP and windows 7, I would have thought there is no difference. Perhaps by chance on XP you were sending some data just after you unplugged the cable which triggered Connected to be set to false?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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