TCP data occasionally received in wrong order and incomplete

我怕爱的太早我们不能终老 提交于 2019-12-23 19:03:27

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/12622435/tcp-data-occasionally-received-in-wrong-order-and-incomplete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!