Hi,
I wrote a TCP Server tool which communicate with microcontroller. I use BackgroundWorker for threading. Here is my listen sub :
My problem is that i can't catch unexpected disconnects (when network cable is unpluged from client microcontorller or when microcontorller shut down)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
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.




Reply With Quote
