Question

I have created TCP Server application in Java, and a client application in C#. When i am sending data, the client sometimes receives data out of order, and sometimes parts miss entirely. Basically, the code i use in the server (java) looks like this (stripped):

ServerSocket welcomeSocket = new ServerSocket(port);
Socket connectionSocket = welcomeSocket.accept();

outputStream = new DataOutputStream(socket.getOutputStream()); //Create stream
outputStream.writeBytes(message + "\n");
outputStream.flush();

I use "\n" as a delimiter. On the client side (C#) i use the following code:

private const char Delimiter = '\n';

tcpclnt = new TcpClient();
tcpclnt.NoDelay = true;
tcpclnt.Client.DontFragment = true;
tcpclnt.Connect(ip, port);

//This function is executed in a separate thread
public void Receive() 
{
try
{
    stream = tcpclnt.GetStream();
    streamreader = new StreamReader(stream);
    this.Connected = true;
    while (Connected)
    {
        string line = ReadLine(streamreader);
        Console.WriteLine("Received data: " + line);
    }
}
}

private string ReadLine(StreamReader reader)
{
    bool finished = false;
    string line = "";

    while (finished == false)
    {
        int asciiNumber = reader.Read();
        char character = Convert.ToChar(asciiNumber);

        if (!character.Equals(Delimiter))
            line += character;
        else finished = true;
    }

    return line;
}

The code is not very complicated. However, the data sent from the server is not always received correctly in the client. As an example, I should receive the following two strings: "5_8_1" and "6_LEVELDATA"

What i get (sometimes) however, is this: "5_8_61" and "_LEVELDATA"

Another example: "5_4_1" and "6_LEVELDATA" result in one single string: "5_6_LEVELDATA"

This seems like some small problem, but it does in fact pretty much ruin my application. I have read a lot of posts, but the only answers i have read are either "this shouldnt happen with TCP" or "send the length of the tcp message first" which would not help in any way in this case, because the problem isn't the data being split up in multiple packages, it simply isn't arriving in the right order, which is something TCP should do.

I am 100% sure the string is always complete before it is being sent by the Java application.

I really wonder what i'm doing wrong here. Is something messed up bad in my code? I would appreciate any help with this problem. Thanks in advance.

Was it helpful?

Solution

After trying Wireshark, it appears my problem existed in the server. Apparently every TCP-message was sent in a seperate thread. Thank you for all of your comments! My problem is solved now.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top