【问题标题】:How to properly handle disrupted TCP connection?如何正确处理中断的 TCP 连接?
【发布时间】:2010-12-19 20:45:26
【问题描述】:

我在服务器程序和客户端程序之间使用 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

【问题讨论】:

    标签: vb.net sockets tcp


    【解决方案1】:

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

    【讨论】:

    • 谢谢!你的意思是这个错误会被try/catch正确处理,我不应该改进这个逻辑吗?然而,在这种情况下,我仍然必须缺少一些东西,因为当我重新启动客户端时我无法连接......正如它所说的“目标机器主动拒绝......”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-25
    • 2020-06-01
    • 2021-10-23
    • 2013-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多