An existing connection was forcibly closed by the remote host

Mosteck

Active member
Joined
Nov 23, 2008
Messages
31
Location
Toronto
Programming Experience
3-5
I wrote a piece of code that will monitor a TCP/IP port for data that is sent out from another system upon completion of its task. This information is then placed in a database.

It runs fine but every once in awhile I get a 'An existing connection was forcibly closed by the remote host' and the program stops.

The code I'm using is:

VB.NET:
    ' Station #10 Torque RS232/Ethernet Logic

    Private Sub Stn10TorqueConnectCallback(ByVal ar As IAsyncResult)

        Stn10TorqueClientSocket.EndConnect(ar)
        Dim Stn10TorqueBytes(4095) As Byte
        Stn10TorqueClientSocket.BeginReceive(Stn10TorqueBytes, 0, Stn10TorqueBytes.Length, SocketFlags.None, AddressOf Stn10TorqueReceiveCallback, Stn10TorqueBytes)

    End Sub

    Private Sub Stn10TorqueReceiveCallback(ByVal ar As IAsyncResult)

        Dim Stn10TorqueBytes() As Byte = CType(ar.AsyncState, Byte())
        Dim Stn10TorqueNumBytes As Int32 = Stn10TorqueClientSocket.EndReceive(ar)

        If Stn10TorqueNumBytes = 0 Then

            Stn10TorqueClientSocket.Shutdown(SocketShutdown.Both)
            Stn10TorqueClientSocket.Close()

        Else

            Stn10TorqueComInd.BackColor = Color.Green

            Dim Stn10TorqueRecv As String = Stn10TorqueASCII.GetString(Stn10TorqueBytes, 0, Stn10TorqueNumBytes)

            'Clear the buffer
            Array.Clear(Stn10TorqueBytes, 0, Stn10TorqueBytes.Length)

            'Store data
            Dim Stn10TorqueDlg As New Stn10TorqueOneStringDelegate(AddressOf Stn10TorqueStoreReceivedData)
            Dim Args() As Object = {Stn10TorqueRecv}
            Me.Invoke(Stn10TorqueDlg, Args)

            Stn10TorqueComInd.BackColor = Color.LightGray

            'Begin Receive again
            Stn10TorqueClientSocket.BeginReceive(Stn10TorqueBytes, 0, Stn10TorqueBytes.Length, SocketFlags.None, AddressOf Stn10TorqueReceiveCallback, Stn10TorqueBytes)

        End If
    End Sub

    Private Sub Stn10TorqueStoreReceivedData(ByVal Data As String)

        ' Coded String:
        ' 1086 Sp:01-01    X.XX Nm          XX
        '                  Torque           Angle

        Dim DecodeTorque As String
        Dim DecodeAngle As String
        Dim DecodeLenght As Integer

        DecodeLenght = Data.Length

        If Mid(Data, 1, 1) <> "#" Then

            DecodeTorque = Mid(Data, (DecodeLenght - 30), 15)
            DecodeAngle = Mid(Data, (DecodeLenght - 15), 15)

            If Stn10ValveTorqueLH = True Then

                Stn10LHCoverScrewTextBox.Text = "Torque=" & RemoveSpaces(DecodeTorque) & " Angle=" & RemoveSpaces(DecodeAngle) & " deg"
                Stn10ValveTorqueLH = False

            ElseIf Stn10ValveTorqueRH = True Then

                Stn10RHCoverScrewTextBox.Text = "Torque=" & RemoveSpaces(DecodeTorque) & " Angle=" & RemoveSpaces(DecodeAngle) & " deg"
                Stn10ValveTorqueRH = False

            End If

        End If

    End Sub

    Private Delegate Sub Stn10TorqueOneStringDelegate(ByVal Data As String)
    ' Thread occupying private sub

Anyone know what can/is causing this and how to prevent it from happening? This database program is unmanned and I can't have it go down this often.

Thanks!!!
 
From what I get, this message appears when the server breaks the connection to its client.

My lucky guess is that there is a time out on the server, maybe because it has too much work to do at the same time and eventually chokes. Can you try to remove the processing and database access and see if things get more stable? If so, you'll have to optimize to shorten the amount of clock time taken by each request to the server.

Maybe you can detemine a certain set of data that makes the server die too.

Last thing I can think of if to add event handling and just log the error instead of crashing and recreate the connection. Try to collect as much data in the log file in case you can pinpoint what is causing the error.

I can't pinpoint a specific cause, but I hope these guesses help your search...
 
It seems to happen even when the application is just sitting idle. The device I'm connecting to is a simple RS232 to Ethernet adapter which I assumes basically only passes information from the RS232 to an Ethernet protocal.

There is no database calls yet, the program is simply just displaying information gathered in various textboxes on the screen. I'm planning on writting the data to a database next, but this is worrying me a bit.

I'm not a profesional programmer, just do some programming like this on a "as needed" basis. I do appriciate your assistance.
 
In case it helps anyone, the error occures on this line:

Dim Stn10TorqueNumBytes As Int32 = Stn10TorqueClientSocket.EndReceive(ar)

This is the Exception Details that I get:

System.Net.Sockets.SocketException was unhandled
ErrorCode=10054
Message="An existing connection was forcibly closed by the remote host"
NativeErrorCode=10054
Source="System"
StackTrace:
at System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult)
at IADC_2008_06_021.IADC_MainScreen.Stn10TorqueReceiveCallback(IAsyncResult ar) in C:\IADC_2008-06-021\IADC_2008-06-021\IADC_MainScreen.vb:line 2159
at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
at System.Net.ContextAwareResult.CompleteCallback(Object state)
at System.Threading.ExecutionContext.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Net.ContextAwareResult.Complete(IntPtr userToken)
at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
at System.Net.Sockets.BaseOverlappedAsyncResult.CompletionPortCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
InnerException:
 
Documentation says EndReceive method may throw exceptions, among them SocketException, so you must catch exceptions at some level or another with all calls to this method. Why the remote host closed the connection you have to ask/see at other end, it could be idle timeout for example, but here you just have to deal with the possibility of exceptions, Try-Catch. I guess it would be interpreted as "remote close" also if other connection problems occured, like if someone unplugged the wire.
Stn10TorqueReceiveCallback:
Stn10TorqueComInd.BackColor = Color.Green
This should throw your application into an exception too, as you can't access controls created on different threads.
 
Showing my newbie/unexperienced side, is there a way to catch this and attempt to connect again?

If not with my code, is there possibly other code that would work better in my situation that just monitors the port of an IP address for data strings?

Thank you for your help!
 
Yes, you can catch it with Try-Catch as I said.
 
Once the try-catch catches the exception, how is it possible to restart the socket?

I'm assuming that using the Socket.Shutdown(SocketShutdown.Both) and Socket.Close() will cleanly close the socket, but now how would you restart it without restarting the application?

Thanks!
 
Connect same way you connected first time.
 
Back
Top