I have written several small programs that communicate via TCP. I have endless problems with the system freezing because one program closed its network connection, and the other endpoint for some reason did not notice that it was now disconnected.
I was expecting I / O on a TCP connection that was closed to throw some kind of I / O exception, but instead, the program seems to just freeze, waiting for the other endpoint to respond. Obviously, if the connection is closed, this answer never comes. (It doesn't even seem to time out if you leave it, say, twenty minutes.)
Is there a way to make the remote end “see” that I have closed the network connection?
Update: Here is the code ...
public sealed class Client { public void Connect(IPAddress target) { var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(ipAddress, 1177); _stream = new NetworkStream(socket); } public void Disconnect() { _stream.Close(); } } public sealed class Server { public void Listen() { var listener = new TcpListener(IPAddress.Any, 1177); listener.Start(); var socket = listener.AcceptSocket(); _stream = new NetworkStream(socket); ... } public void Disconnect() { socket.Shutdown(SocketShutdown.Both); socket.Disconnect(false); } }
source share