开发者

How to handle TCPListener "An existing connection was forcibly closed by the remote host"

I have a tcp server that uses TCPListener and the async method BeginAcceptTCPClient:

 Imports System.Net.Sockets
Imports System.Threading
Imports System.Net

Public Class TCPServer
    Private mPort As Integer
    Public Event IncomingMessage(ByVal Message As String, ByVal IP As String)
    'This signals threadpool threads to stop...
    Private mStopServer As ManualResetEvent
    Private mListener As TcpListener
    Public Sub New(ByVal Port As Integer)
        mPort = Port
        Start()

    End Sub

    Public Sub Start()
        Try
            If mListener Is Nothing Then
                mListener = New TcpListener(IPAddress.Any, mPort)
            End If

            mListener.Start()
            AcceptClients()
            mStopServer = New ManualResetEvent(False)
        Catch ex As Exception
            ExceptionHandling.LogError(ex)开发者_如何学Python
        End Try

    End Sub

    Private Sub AcceptClients()
        Try
            Dim result As IAsyncResult = mListener.BeginAcceptTcpClient(AddressOf HandleAsyncConnection, mListener)
        Catch ex As Exception
            ExceptionHandling.LogError(ex)
        End Try

    End Sub

    Dim so As New Object
    Public Sub StopListening()
        Try
            mStopServer.Set()
            mListener.Stop()
        Catch ex As Exception
            ExceptionHandling.LogError(ex)
        End Try

    End Sub


    Private Sub HandleAsyncConnection(ByVal result As IAsyncResult)
        Try


            If Not mStopServer.WaitOne(0) Then
                Dim listener As TcpListener = DirectCast(result.AsyncState, TcpListener)
                If listener Is Nothing Then Exit Sub
                Dim client As TcpClient = listener.EndAcceptTcpClient(result)
                Trace.WriteLine("Connected to new client")
                ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf ProcessClient), client)
                AcceptClients()

            End If
        Catch ex As Exception
            ExceptionHandling.LogError(ex)

        End Try
    End Sub



    Private Sub ProcessClient(ByVal client As Object)

        Dim newClient As TcpClient = DirectCast(client, TcpClient)


        Try
            ' Buffer for reading data
            Dim bytes As Byte() = New Byte(32 * 1024) {}
            Dim clientData As New System.Text.StringBuilder()


            Using ns As NetworkStream = newClient.GetStream()
                ' set initial read timeout to 1 minute to allow for connection
                ns.ReadTimeout = 60000
                ' Loop to receive all the data sent by the client.
                Dim bytesRead As Integer = 0
                Do
                    ' read the data
                    Try
                        If mStopServer.WaitOne(0) Then Exit Sub

                        bytesRead = ns.Read(bytes, 0, bytes.Length)
                        If bytesRead > 0 Then
                            clientData.Append(System.Text.Encoding.UTF8.GetString(bytes, 0, bytesRead))
                            ' decrease read timeout to 1 second now that data is coming in
                            ns.ReadTimeout = 1000
                        End If

                    Catch ioe As IO.IOException
                        Trace.WriteLine(ioe.ToString)
                        bytesRead = 0
                        Dim bError() As Byte = Error400()
                        ns.Write(bError, 0, bError.Length)

                    End Try

                Loop While ns.DataAvailable
                ForwardData(clientData.ToString, newClient.Client.RemoteEndPoint.ToString)
                'Trace.Write(clientData.ToString())
                'Acknowledge success
                bytes = Ack200()
                ns.Write(bytes, 0, bytes.Length)
            End Using

        Catch ex As Exception
            ExceptionHandling.LogError(ex)

        Finally
            ' stop talking to client
            If newClient IsNot Nothing Then
                newClient.Close()
            End If
        End Try
    End Sub

    Private Sub ForwardData(ByVal Data As String, ByVal IP As String)
        RaiseEvent IncomingMessage(Data, IP)
    End Sub
    Public Function Ack200() As Byte()
        Return System.Text.Encoding.UTF8.GetBytes("Okay")
    End Function

    Public Function Error400() As Byte()
        Return System.Text.Encoding.UTF8.GetBytes("Error")
    End Function

End Class

My problem is that infrequently, I get an exception in the HandleAsyncConnection method: "An existing connection was forcibly closed by the remote host" right at the EndAcceptTCPClient method. At this point, the TCPListener seems to stop listening. The problem is that I can't test this easily, as it only happens on a remote test VM and only once every 24 hours or so. If I knew how to recreate the error with a test client, I would be able to figure this out. Wireshark shows a reset [RST] packet being sent at around the time of the exception. So I either need to know how to handle the exception, or how to recreate the problem with a test client.


You can recreate the problem by rebooting the server, or bouncing the service you are connected to. Basically anything that kill the process you are communicating with should generate this error.

To handle, you pretty much just have to catch the exception and try reconnecting to the server, possibly having to wait till its available again.

Edit: Your code stops listening because you're call to AcceptClients is after where the exception occurs, so you never get back to the BeginAcceptTCPClient function. Also, and i'm not sure how this works with the Async calls, but it looks like an infinite recursion to me. BeginAcceptTCP client calls a delegate to HandlAsynConnection, which calls AcceptClients, which starts the loop over. In my mind you should get a stack overflow error after so many connections. You could add a finally clause to your try block in HandleAsyncConnection and call it there, so it always gets called in event of error.

    Try


        If Not mStopServer.WaitOne(0) Then
            Dim listener As TcpListener = DirectCast(result.AsyncState, TcpListener)
            If listener Is Nothing Then Exit Sub
            Dim client As TcpClient = listener.EndAcceptTcpClient(result)
            Trace.WriteLine("Connected to new client")
            ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf ProcessClient), client)

        End If
    Catch ex As Exception
        ExceptionHandling.LogError(ex)
    Finally            
        AcceptClients()
    End Try
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜