Hi, the MSDN page on Socket.Connected gives code to show how to determine if the socket is actually connected as of the current time, since Socket.Connected only reflects the state of the connection as of the most recent operation:
http://msdn2.microsoft.com/en-us/library/system.net.sockets.socket.connected.aspx
How does the above code work if Console.WriteLine("Connected!") is run immediately after client.Send(tmp, 0, 0)? Wouldn't it always say it is connected due to client.Blocking = False allowing the execution to immediately continue?
The MSDN page on Socket.Blocking says:
http://msdn2.microsoft.com/en-us/library/system.net.sockets.socket.blocking.aspx
http://msdn2.microsoft.com/en-us/library/system.net.sockets.socket.connected.aspx
VB.NET:
[COLOR=green]' This is how you can determine whether a socket is still connected.[/COLOR]
[COLOR=blue]Dim[/COLOR] blockingState [COLOR=blue]As[/COLOR] [COLOR=blue]Boolean[/COLOR] = client.Blocking
[COLOR=blue]Try[/COLOR]
[COLOR=blue]Dim[/COLOR] tmp(0) [COLOR=blue]As[/COLOR] [COLOR=blue]Byte[/COLOR]
client.Blocking = [COLOR=blue]False[/COLOR]
client.Send(tmp, 0, 0)
Console.WriteLine([COLOR=maroon]"Connected!"[/COLOR])
[COLOR=blue]Catch[/COLOR] e [COLOR=blue]As[/COLOR] SocketException
[COLOR=green]' 10035 == WSAEWOULDBLOCK[/COLOR]
[COLOR=blue]If[/COLOR] e.NativeErrorCode.Equals(10035) [COLOR=blue]Then[/COLOR]
Console.WriteLine([COLOR=maroon]"Still Connected, but the Send would block"[/COLOR])
[COLOR=blue]Else[/COLOR]
Console.WriteLine([COLOR=maroon]"Disconnected: error code {0}!"[/COLOR], e.NativeErrorCode)
[COLOR=blue]End[/COLOR] [COLOR=blue]If[/COLOR]
[COLOR=blue]Finally[/COLOR]
client.Blocking = blockingState
[COLOR=blue]End[/COLOR] [COLOR=blue]Try[/COLOR]
Console.WriteLine([COLOR=maroon]"Connected: {0}"[/COLOR], client.Connected)
How does the above code work if Console.WriteLine("Connected!") is run immediately after client.Send(tmp, 0, 0)? Wouldn't it always say it is connected due to client.Blocking = False allowing the execution to immediately continue?
The MSDN page on Socket.Blocking says:
http://msdn2.microsoft.com/en-us/library/system.net.sockets.socket.blocking.aspx
If you want execution to continue even though the requested operation is not complete, change the Blocking property to false.