Search code examples
c#tcpconsolepacketsnetstream

C# - Seems to be receiving two TCP packets at once?


I'm making a chatroom application, and I send TCP packets to communicate between the server and the client.

I have the following code:

string returnMessage = "[EVT]USERSUCCESS";
                bytes = Encoding.ASCII.GetBytes(returnMessage);
                info.WriteToStream(bytes);

                foreach (ConnectionInfo con in connections)
                {
                    info.WriteToStream(bytes);
                    bytes = Encoding.ASCII.GetBytes("[EVT]USERJOIN;" + username);
                    con.WriteToStream(bytes);
                }

However, when the client reads this, the response is:

  • [EVT]USERSUCCESS[EVT]USERJOIN;Name

Which seems as though it is receiving both packets at once..?

This is the code I have for receiving:

static void ServerListener()
    {
        while (true)
        { 
            byte[] bytes = new byte[1024];
            int numBytes = stream.Read(bytes, 0, bytes.Length);
            string message = Encoding.ASCII.GetString(bytes, 0, numBytes);

            if (HandleResponse(message) && !WindowHasFocus())
            {
                player.Play();
            }      
        }
    }

Which is run as a separate thread. HandleResponse() is fully working.

Thanks in advance!


Solution

  • Tcp is a stream protocol not a packet protocol.

    You could get the bytes in mutiple packets or a single packet like you are doing.

    What you need to do is put a byte that siginifies the end of a packet (such as the null byte)

    Psudeo code:

    1. Have a buffer that you add every byte received to.
    2. If their is a null byte in the buffer then split the buffer at the null byte
    3. Handle the left side as a complete packet. Keep the right side in the buffer until you get a new null byte.

    Advanced TCP:

    1. You may want to add your own error checking in your "packet"