3

I have used a Asynchronous TCP/IP server, everything works fine but when a client disconnects due to error or forced exit of the application it also closes my server due to an exception of type IO.IOException. The exception occurs in the following sub:

   Private Sub ReadCallback(ByVal result As IAsyncResult)
        Try


            Dim client As Client = TryCast(result.AsyncState, Client)
            If client Is Nothing Then
                Return
            End If
            'MsgBox(client.ClientID)
            Dim networkStream As NetworkStream = client.NetworkStream
            Dim read As Integer = networkStream.EndRead(result) **' ERRORS HERE!**
            If read = 0 Then
            Dim client As Client = TryCast(result.AsyncState, Client)
            SyncLock Me.Clients
                Me.Clients.Remove(Client.ClientID)
                Return
            End SyncLock
            End If

The below code throws an IO.IOException when a client disconnects from my TCP Server:

Dim read As Integer = networkStream.EndRead(result) **' ERRORS HERE!**

Other then catching the IO.IOException how can I prevent this from creating the exception in the first place. Basically I'd like to remove my client when this scenario occurs, at the moment as a work around I have removed the client on an IO.IOException and rethrown the method. Would rather a better method.

Tyson
  • 149
  • 3
  • 14
  • what type is `client`? Most of the classes that use socket have a connected property. check this is true after you check the client is not null. if it's false, you've been disconnected – Simon Halsey Aug 12 '12 at 14:49
  • @SimonHalsey Not so. The isConnected() and isClosed() methods only tell you what you have done to the socket, i.e. your endpoint. They don't tell you about the state of the connection, and they specifically do not behave as you have just described. – user207421 Aug 13 '12 at 00:28
  • You are correct. It was a bad choice of words. I was thinking about if you closed the connection, not if the connection was closed remotely. – Simon Halsey Aug 14 '12 at 16:49

2 Answers2

2

The exception is the way. There is no TCP API or callback that tells you about broken connections. You have to read or write to find out. This was designed deep into TCP for reliability reasons.

user207421
  • 305,947
  • 44
  • 307
  • 483
1

Hope this helps :

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    IAsyncResult result = socket.BeginConnect(_ip, Port, null, null);
    bool success = result.AsyncWaitHandle.WaitOne(500, true); // 500 is milisecods to wait
     if (socket.Connected && socket.IsBound && success)
     {
          // do your work                          
     }else
    {
     // open a new connection or show your message to user
    }
Erhan A
  • 691
  • 11
  • 21