Search code examples
c#multithreadingunity-game-enginetcp

How to fix commands concatenation when enqueuing ConcurrentQueue<string> in unity3d c#?


Good day. Wrote 2 applications communicating with each other over TCP. One is a server (tablet), the second is a client (windows). To synchronize multithreading, I used the standard ConcurrentQueue queue class. However, I noticed strange behavior when sending messages. When added to a queue, commands are concatenated, although commands are sent in turn. it's look lite two commands(2 string) executing at one time, then concatenating, then enqueuing 2 queue. Look like this: enter image description here


Solution

  • TCP doesn't do messages. TCP does streams. The problem isn't the concurrent queue - it's how you read the string.

    One send can result in multiple receives on the other side. Multiple sends can result in a single receive. That's how TCP works.

    To send messages over TCP, you have to use message framing - have a way of dividing the stream of bytes into individual messages.

    There's two extremely simple (and stupid) message framing approaches:

    • Terminate each message with a special terminator value. This is often used in text-based TCP protocols, and the terminator is often something like \n
    • Prefix each message with its length. The reading then becomes a loop of "read message length, then read length of bytes".

    But in the end, TCP is complicated. If you can, use a ready networking library instead of trying to deal with TCP directly, something like Lidgren. These allow you a much more high-level approach to networking code - e.g. having messages, some reliable, some unreliable etc.