3

我使用了异步 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 上的客户端并重新抛出该方法。宁愿有更好的方法。

4

2 回答 2

2

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

于 2012-08-13T00:27:25.313 回答
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
    }
于 2012-08-13T01:11:22.463 回答