Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6218793
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T07:40:14+00:00 2026-05-24T07:40:14+00:00

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

  • 0

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)
        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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T07:40:15+00:00Added an answer on May 24, 2026 at 7:40 am

    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
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

No related questions found

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.