Nosrama
Nosrama

Reputation: 14964

How do I make a non-blocking socket call in C# to determine connection status?

the MSDN docs for the Connected property on Socket say the following:

The value of the Connected property reflects the state of the connection as of the most recent operation. If you need to determine the current state of the connection, make a nonblocking, zero-byte Send call. If the call returns successfully or throws a WAEWOULDBLOCK error code (10035), then the socket is still connected; otherwise, the socket is no longer connected.

I need to determine the current state of the connection - how do i make a non-blocking, zero-byte send call?

Upvotes: 7

Views: 8322

Answers (3)

colbybhearn
colbybhearn

Reputation: 482

Just providing additional info based on experience: The comments at the bottom of versions 3.5 and 4 of that documentation page for Socket.Connect describe my experience - the example simply didn't work. Really wish I knew why it works for some and not others.

As a work-around, despite what the documentation says, I changed the sample to actually send the 1 byte with no flags. This successfully updated the state of Connected property, and is equivalent to sending a keep-alive packet at an interval.

Upvotes: 0

Matt Davis
Matt Davis

Reputation: 46062

The example at the bottom of MSDN documentation for the Socket.Connected property (at least the .NET 3.5 version) shows how to do this:

// .Connect throws an exception if unsuccessful
client.Connect(anEndPoint);

// This is how you can determine whether a socket is still connected.
bool blockingState = client.Blocking;
try
{
    byte [] tmp = new byte[1];

    client.Blocking = false;
    client.Send(tmp, 0, 0);
    Console.WriteLine("Connected!");
}
catch (SocketException e) 
{
    // 10035 == WSAEWOULDBLOCK
    if (e.NativeErrorCode.Equals(10035))
        Console.WriteLine("Still Connected, but the Send would block");
    else
    {
        Console.WriteLine("Disconnected: error code {0}!", e.NativeErrorCode);
    }
}
finally
{
    client.Blocking = blockingState;
}

 Console.WriteLine("Connected: {0}", client.Connected);

Upvotes: 8

user47589
user47589

Reputation:

Socket.BeginSend

Upvotes: 3

Related Questions