开发者

Simulate Socket Hard Disconnect

开发者 https://www.devze.com 2023-01-15 03:36 出处:网络
I have a C# app where a server and some clients communicate from different machines using sockets. Most of the time, the server detects a dis-connect correctly when it receives 0 bytes in the sock.Re

I have a C# app where a server and some clients communicate from different machines using sockets.

Most of the time, the server detects a dis-connect correctly when it receives 0 bytes in the sock.Receive(...) call. But when there is a hardware issue (say a network cable is unplugged), there is a problem. One server thread continues to block on sock.Receive(...) because it doesn't know the connection is lost. I was going to add a heartbeat message to detect this, but I开发者_C百科 wanted to test it in dev.

But I'm not sure how I can test this case without an actual hardware issue. Even when I just kill the client process, the socket somehow manages to dis-connect gracefully (that is, the server does a read of 0 bytes). It's only when I physically unplug the client machine from the network that I see this issue.

Is there any way that I can simulate this issue in dev?


You need to explicitly inform WinSock that you don't want it to clean up for you after closing the socket. This is done by setting LingerState as such:

socket.LingerState = new LingerOption(true, 0);
socket.Close();

LingerState is a bit confusing, because if you disable the linger, WinSock will actually linger but just not block your program. You have to enable the linger and set the linger timeout to zero in order to force WinSock to drop the connection.

P.S. If you want some info about keepalive packets (heartbeats), I've written a blog entry on the subject.

Update:

I re-read your question (and comment), and my answer is wrong...

The code above will simulate an abortive close, not a half-open situation. There isn't a way to simulate a half-open situation in software; you need to unplug an Ethernet cable that is not attached to either computer in order to test this (e.g., yank the cable between the two switches in this configuration: computer A <-> switch <-> switch <-> computer B).

0

精彩评论

暂无评论...
验证码 换一张
取 消