TCP client/server not thread safe

Hi,

I have two .NET apps of which one is set up as a TCP server to receive data and one as TCP client sending data. Some of the messages received on the server app however are being concatenated every now and then. I think this means that thread safety is missing at some level but haven’t got a clue what I’m doing wrong here.

I have simplified both apps, see code below. Whenever text is concatenated it will write the received message to the console.

Client code:

Module Module1
Private client As GSF.Communication.TcpClient

Sub Main()

    client = New GSF.Communication.TcpClient()
    client.ConnectAsync()

    Do

        If client.CurrentState = GSF.Communication.ClientState.Connected Then

            Dim t As Threading.Thread
            For intRow As Integer = 0 To 9999

                t = New Threading.Thread(AddressOf DoSomething)
                t.Start("HELLO")

            Next intRow

            Exit Do

        End If

    Loop

End Sub
Private Sub DoSomething(message As String)

    client.SendAsync(message)

End Sub

End Module

And the TCP server app:

Public Class Form1

Public WithEvents server As GSF.Communication.TcpServer

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load

    server = New GSF.Communication.TcpServer()
    server.Start()

End Sub

Private Sub server_ReceiveClientDataComplete(sender As Object, e As EventArgs(Of Guid, Byte(), Integer)) Handles server.ReceiveClientDataComplete

    Dim strMessage As String = System.Text.Encoding.ASCII.GetString(e.Argument2)

    If Not strMessage.Length = 5 Then ' HELLO
        System.Console.WriteLine(strMessage)
    End If

End Sub

End Class

Help on this would be much aprreciated!

TCP is a streaming protocol. At the OS layer, it’s common for messages to be concatenated to save on TCP overhead and increase data throughput. You’ll either have to prepend the length of the messages, or I believe the TCPClient class has a PayloadAware option that will do this for you.