检测客户端的正确方法已从TCP / IP断开

时间:2012-08-12 11:58:18

标签: c# vb.net asynchronous tcp tcpserver

我使用过异步TCP / IP服务器,一切正常但是当客户端由于错误或强制退出应用程序而断开连接时,由于IO.IOException类型的异常,它也会关闭我的服务器。例外情况发生在以下子句中:

   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

当客户端断开与TCP服务器的连接时,以下代码会抛出IO.IOException:

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

然后捕获IO.IOException,我怎么能阻止它首先创建异常。基本上我想在发生这种情况时删除我的客户端,此时作为解决方法,我已经删除了IO.IOException上的客户端并重新抛出了该方法。宁愿采用更好的方法。

2 个答案:

答案 0 :(得分:2)

异常的方式。没有TCP API或回调可以告诉您有关连接断开的信息。你必须阅读或写作才能找到答案。出于可靠性原因,这是在TCP深入设计的。

答案 1 :(得分:1)

希望这会有所帮助:

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
    }