I have a TCP listener working but doesn't send anything. To get this TCP listener working I have a thread in a endless loop.
Now I need to answer to some specific packets and also be able to send data when the user request it using the same port that the TCP listener is using. The remote device keeps the connection open to be able to receive new data.
So, I must to create a new TCP client to send data to the current connected client or use the current listener socket?
Public Sub StopServer()
TcpOpen = False
Server.Stop()
ServerThread = Nothing
End Sub
Public Sub InitServer(ByVal Port As Integer)
Server = New TcpListener(IPAddress.Any, Port)
ServerThread = New Thread(AddressOf ConnectionListener)
ServerThread.IsBackground = True
ServerThread.Start()
TcpOpen = True
End Sub
Private Sub ConnectionListener()
Server.Start()
While True
If TcpOpen Then
If Server.Pending Then
Dim client As TcpClient = Server.AcceptTcpClient()
Dim T As New Thread(AddressOf StartTcpClient)
client.ReceiveBufferSize = 128000
T.IsBackground = True
T.Start(client)
Else
System.Threading.Thread.Sleep(10)
End If
Else
Exit While
End If
End While
End Sub
Private Sub StartTcpClient(ByVal client As TcpClient)
Dim bytesRead As Integer
Dim RxBuffer(1500) As Byte 'Original 1024
Dim RxDataStr As String = ""
Dim TxBuffer(1500) As Byte
Dim TxDataStr As String = ""
Dim TempData As String
Dim DataReceived As Boolean = False
Dim TimeX As Integer = 0
Dim RemoteIP As Net.IPEndPoint = client.Client.RemoteEndPoint
Dim RemoteIPStr As String = RemoteIP.Address.ToString
WriteRTBLog("Se inicio una nueva conexion TCP con la IP " & RemoteIPStr, Color.DarkViolet)
WriteRTBLog("Esperando datos...", Color.Black)
client.ReceiveTimeout = 30000
Try
While True
If client.GetStream.DataAvailable Then
bytesRead = client.GetStream.Read(RxBuffer, 0, RxBuffer.Length)
TimeX = 0 'Reset timer
If bytesRead > 0 Then
TempData = System.Text.ASCIIEncoding.UTF8.GetString(RxBuffer, 0, bytesRead) 'UTF8
RxDataStr += TempData
If Not DataReceived Then
DataReceived = True
WriteRTBLog("Se estan recibiendo datos...", Color.Purple)
End If
If RxDataStr.Contains("<") Then
'Process data
TxDataStr = AnswerProcessor(RxDataStr)
'New code- trying to send data
If TxDataStr.Length > 5 Then
TxBuffer = System.Text.Encoding.ASCII.GetBytes(TxDataStr)
client.Client.Send(TxBuffer)
End If
RxDataStr = "" 'Clean buffer
End If
End If
Else
If Not client.Connected Then
Exit While 'Close connection
Else
System.Threading.Thread.Sleep(10)
End If
End If
End While
If RxDataStr.Length > 0 Then
WriteRTBLog(String.Format("Se recibieron {0} bytes desde {1}", RxDataStr.Length.ToString, RemoteIPStr), Color.ForestGreen)
If Not client.Connected Then
WriteRTBLog("Conexion cerrada", Color.Black)
End If
End If
Catch ex As Exception
client.Close()
WriteRTBLog("Error en la conexion a " & RemoteIPStr, Color.Red)
WriteRTBLog(ex.Message, Color.Red)
WriteRTBLog(ex.StackTrace, Color.Red)
If RxDataStr.Length > 0 Then
' Create the file.
Dim PathX As String = Application.StartupPath & "\TCP_File_err" & CLng(DateTime.UtcNow.Subtract(New DateTime(1970, 1, 1)).TotalMilliseconds) & ".TCP"
Using fs As FileStream = File.Create(PathX)
Dim data As Byte() = New ASCIIEncoding().GetBytes(RxDataStr)
' Add some information to the file.
fs.Write(data, 0, data.Length)
End Using
WriteRTBLog(String.Format("Se recibieron {0} bytes desde {1} y se guardaron en {2}.", RxDataStr.Length.ToString, RemoteIPStr, PathX), Color.ForestGreen)
End If
End Try
End Sub