如何正确处理中断的TCP连接?

时间:2010-12-19 20:45:26

标签: vb.net sockets tcp

我在服务器程序和客户端程序之间使用TCP套接字连接。多个客户端程序应连接到同一端口。问题是,如果我关闭客户端程序,我会在服务器程序上收到以下错误:

System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
   at System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult)
   at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)

http://i55.tinypic.com/nh135w.png

如果我通过try / catch处理这个问题,那么我无法重新连接客户端程序,因为它会给出以下错误(在客户端程序中):

No connection could be made because the target machine actively refused it 127.0.0.1: 1234

以下是服务器程序中的监听器代码。我希望得到一些帮助,以了解如何在没有服务器程序失败的情况下处理客户端程序关闭/重启和重新连接。

   ' This is the callback function for TcpClient.GetStream.Begin, It begins an asynchronous read from a stream.
    Private Sub DoRead(ByVal aread As IAsyncResult)
        Dim BytesRead As Integer
        Dim strMessage As String

        ' Try
        ' Ensure that no other threads try to use the stream at the same time.
        SyncLock _client.GetStream
            ' Finish asynchronous read into readBuffer and get number of bytes read.
            If Client.Connected Then
                BytesRead = _client.GetStream.EndRead(aread)
            End If
        End SyncLock

        ' Convert the byte array the message was saved into, minus one for the Chr(13) (carriage return).
        strMessage = Encoding.ASCII.GetString(readBuffer, 0, BytesRead - 1)
        ProcessIncoming(strMessage)

        ' Ensure that no other threads try to use the stream at the same time.

        SyncLock Client.GetStream
            ' Start a new asynchronous read into readBuffer.
            Client.GetStream.BeginRead(readBuffer, 0, READ_BUFFER_SIZE, AddressOf DoRead, Nothing)
        End SyncLock
        'Catch e As Exception
        '    ' This triggers if userlist is found empty
        '    ' Then gives problem, as it cant close the connection or something.. ??
        '    Debug.Print("UserConnection.DoRead Exception: " & e.ToString)
        '    CloseConnetion("Error: Stream Reciever Exception")

        'End Try

    End Sub

1 个答案:

答案 0 :(得分:1)

你没有。你是服务员。您关闭套接字并忘记它。如果客户想要更多服务,则由他重新连接。