I have a System.Net socket that's spontaneously disconnecting, especially if I query its state TWICE in the Visual Studio 2010 debugger.
It's instantiated like this:
_TCPConn = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Later I connect and set up a loop to watch its "Connected" property . . .
_TCPConn.Connect(this.IPAddress, REMOTE_TCP_PORT);
// loop to figure out why / when we're disconnecting ...
int loops;
bool bState = false;
for (loops = 0; loops < 100; loops++)
{
bState = _TCPConn.Connected;
if (!_TCPConn.Connected)
{
break;
}
Thread.Sleep(1000);
}
Immediately after the Connect call its Connected property is true in the debugger and a network sniffer shows the successful connection with the host.
But if I examine the Connected property a second time in the debugger it shows as false.
If I don't set any breakpoints in the loop it gets all the way through the loop (100 seconds) and when it falls out the Connected property is true the first time I look at in the debugger and false the next time.
If I let it loop for 10 or 15 seconds and breakpoint, it will be true the first time I look in the debugger and false the second time I look at it and it will then fall out of the loop at that point, proving that it's not just an artifact of the debugger - it really is set to false.
When it disconnects there is no associated activity on the network sniffer, i.e., it's not being disconnected by the host.
This is a single-threaded application. I started looking at this because later on when I tried to use my socket I was often finding it disconnected and was trying to figure out why.