Results 1 to 6 of 6

Thread: TCP Server Catching Unexpected Disconnecting

  1. #1

    Thread Starter
    New Member
    Join Date
    Jan 2010
    Posts
    6

    Lightbulb TCP Server Catching Unexpected Disconnecting

    Hi,

    I wrote a TCP Server tool which communicate with microcontroller. I use BackgroundWorker for threading. Here is my listen sub :

    Code:
    Sub listen_port2(ByVal b As BackgroundWorker)
            Dim server As TcpListener
            Dim ts As TimeSpan
            Dim ReturnValue As Integer
            server = Nothing
            Try
    
                Dim port As Int32 = 8081
    
                server = New TcpListener(IP, port)
    
                server.Start()
    
                Dim bytes(1024) As Byte
                Dim data As String = Nothing
               
    
                While True
                    Dim client As Sockets.TcpClient = server.AcceptTcpClient()
                    Dim ipend As Net.IPEndPoint = client.Client.RemoteEndPoint
                    PublicIP = ""
                    If Not ipend Is Nothing Then
                        PublicIP = ipend.Address.ToString
                    End If
                    b.ReportProgress(1)
                    Dim stream As NetworkStream = client.GetStream()
    
                    Dim i As Int32
                    Dim k As Short
                    For k = 0 To 1024
                        bytes(k) = 0
                    Next
                    i = stream.Read(bytes, 0, bytes.Length)
    
                    While (i <> 0)
    
                        Debug.Print(i)
                        data = ""
                        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i)
                        Send_SQL(data)
                        i = stream.Read(bytes, 0, bytes.Length)
                    End While
                    client.Close()
                End While
            Catch e As Exception
                Write_Error("listen_port2" & vbCrLf & e.Message) ' Write exception to a file
            Finally
                server.Stop()
            End Try
        End Sub
    My problem is that i can't catch unexpected disconnects (when network cable is unpluged from client microcontorller or when microcontorller shut down)

    I used a TCP server tools(Hercules) and they behave such : When microcontroller has gone they can't catch it but when microcontroller wants to connect again this tool shows that a disconnect message then it gives a connected message. When i try samething at my code i receive this error :

    "Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host"

    So what should i do for a stable TCP server? And i read sone articles about "TCP KeepAlive". Is it possible to Implement it to my code?


    Your advices will be great help for me.

    Regards.

  2. #2

    Thread Starter
    New Member
    Join Date
    Jan 2010
    Posts
    6

    Re: TCP Server Catching Unexpected Disconnecting

    Bump

  3. #3
    Super Moderator FunkyDexter's Avatar
    Join Date
    Apr 2005
    Location
    An obscure body in the SK system. The inhabitants call it Earth
    Posts
    7,900

    Re: TCP Server Catching Unexpected Disconnecting

    The reason your not getting any answers is that you've posted your question in the codebank section which is intended for working code submissions rather than posting questions and answers. I'm moving your thread to the main forum where, hopefully, you'll get some response.
    The best argument against democracy is a five minute conversation with the average voter - Winston Churchill

    Hadoop actually sounds more like the way they greet each other in Yorkshire - Inferrd

  4. #4
    Sinecure devotee
    Join Date
    Aug 2013
    Location
    Southern Tier NY
    Posts
    6,582

    Re: TCP Server Catching Unexpected Disconnecting

    Quote Originally Posted by simsekm View Post
    ...
    I used a TCP server tools(Hercules) and they behave such : When microcontroller has gone they can't catch it but when microcontroller wants to connect again this tool shows that a disconnect message then it gives a connected message. When i try samething at my code i receive this error :

    "Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host"

    So what should i do for a stable TCP server? And i read sone articles about "TCP KeepAlive". Is it possible to Implement it to my code?...
    It sounds like when the Hercules tool gets the exeception you noted "Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host", it closes the existing port and Listens for a new connection.
    You should do the same.
    Wrap pretty much the code in the whole sub in a loop, so if you get an exception, rather than fall out of the sub, you loop back up (after closing/disposing the old server), and the code at the top will open a new server and way for another connection.

  5. #5

    Thread Starter
    New Member
    Join Date
    Jan 2010
    Posts
    6

    Re: TCP Server Catching Unexpected Disconnecting

    Thanks for this good idea. In fact that I had same idea about it but my barrier was my threads are Backgroundworker . It's not easy to restart it. I tried to client.close() method when I have got this exception but it didn't work. I think backgroundworker object is not a good choice for a TCP server. And my other idea is TCPListener class is not good choice as much as a socket class. What do you think about it?

  6. #6
    Sinecure devotee
    Join Date
    Aug 2013
    Location
    Southern Tier NY
    Posts
    6,582

    Re: TCP Server Catching Unexpected Disconnecting

    Well, I haven't had occasion to use a Background worker, but I don't see that it should be a problem in this case.
    I assume you've kicked off the background worker, and it calls this function passing a reference to itself.
    If everything works well, it looks like the code should loop in this sub forever and continue to receive data.
    All I'm saying is to put a loop around this loop, so you can keep from exiting the sub, so remain active either reading from a connection, or waiting for a connection.

    While I haven't used a background worker for this, I do kickoff background threads to do this type of thing, and which should be for the most part, the same result.
    The reason I haven't used a background worker is that I perceive the use for background workers is to do a job that will take some amount of time and when they're done, should report the job done and exit.
    Since the purpose of a network connection in the cases I've dealt with is to provide a communication path between two or more programs, or machines, it needs to exist for the life of the program, so is just kicked off in a background thread to do its work until we exit.

    So, what I envisioned for your existing code, without too many changes, is just add another loop around what you already have.
    If you get an exception, stop the server, dispose of it, hit the bottom of the outer loop, loop back up and create a new server and listen for another connection. You could change the Write_Error to say you're restarting the connection.
    Code:
    Sub listen_port2(ByVal b As BackgroundWorker)
            Dim server As TcpListener
            Dim ts As TimeSpan
            Dim ReturnValue As Integer
        Do
            server = Nothing
            Try
    
                Dim port As Int32 = 8081
    
                server = New TcpListener(IP, port)
    
                server.Start()
    
                Dim bytes(1024) As Byte
                Dim data As String = Nothing
               
    
                While True
                    Dim client As Sockets.TcpClient = server.AcceptTcpClient()
                    Dim ipend As Net.IPEndPoint = client.Client.RemoteEndPoint
                    PublicIP = ""
                    If Not ipend Is Nothing Then
                        PublicIP = ipend.Address.ToString
                    End If
                    b.ReportProgress(1)
                    Dim stream As NetworkStream = client.GetStream()
    
                    Dim i As Int32
                    Dim k As Short
                    For k = 0 To 1024
                        bytes(k) = 0
                    Next
                    i = stream.Read(bytes, 0, bytes.Length)
    
                    While (i <> 0)
    
                        Debug.Print(i)
                        data = ""
                        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i)
                        Send_SQL(data)
                        i = stream.Read(bytes, 0, bytes.Length)
                    End While
                    client.Close()
                End While
            Catch e As Exception
                Write_Error("listen_port2" & vbCrLf & e.Message) ' Write exception to a file
            Finally
                server.Stop()
                server.Dispose()
            End Try
        Loop
    End Sub
    p.s. To be clear, I don't usually code endless loops like this in my background threads, but loop as long as a boolean flag is true (or false), e.g.
    Code:
      Do While Running  'Loop while running is true (loop while flag is true)
      '...
      Loop
    
      Do Until Leaving  'Loop until Leaving is True (loop while flag is false)
      '...
      Loop
    That way I set the flag when closing the main form to give the loop a chance to exit, and the background thread a chance to exit naturally.

    p.s. Perhaps the Finally clause will need to be reworked, because I'm not sure exactly how that works since we're not actually leaving the Sub at the time of the exception. Anyway, this gives you the general idea of where I was coming from.
    Last edited by passel; Jan 29th, 2015 at 04:12 PM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width