1
votes

i'm working on chat application in c# with a server coded in c++, i can already send and receive messages between my clients. But, my problem now, that a want to define the structure of the TCP packet by myself like :

[numberOfsequence: uint16_t] [id: uint16_t] [data: x] Where:

  1. numberOfsequence: is the number of my packet (to guarantee that in
    receive the packets in order , i know that is automaticly regled by TCP protocol, but i wanna do it also)
  2. id: represente the type of
    operartion (login, message, disconnect) id is gonna be like 0000 for login , 0001 for message ....
  3. Data: information.

          //TO connect
    
            TcpClient clientSocket; 
            NetworkStream serverStream;
            clientSocket.Connect(IPAddress.Parse(textBoxIP.Text), Convert.ToInt32(textBoxPort.Text));
            serverStream = clientSocket.GetStream();
    
    
            //Sending login
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBoxLogin.Text);  
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();
    

So my question is how to define the packet structure ? thanks

1
It guess it can't be possible if you use a TCPClient, tcp and its internal structure is a standard and implemented, as far as i know, on low level hardware base = your network card, to make it fast. - Florian p.i.
If you want to be responsible for package integrity, you have to use another protocol like udp. - Florian p.i.

1 Answers

1
votes

You should include the length of the data field in the packet structure. This is because TCP does not deal with packets but streams. The underlying protocol might slice or combine your packets, which you must then handle and correct yourself.

Thus, if we assume the numberOfSequence and id fields to be fixed-length, but the length of the data field may vary, this is my suggested packet structure:

numberOfSequence: 2 bytes
id: 2 bytes
dlength: 2 bytes
data: dlength bytes

As you can see, the dlength field indicates the length of the data part. The receiving end should parse the dlength information before reading the data field. If the received "packet" contains more bytes than the dlength field indicates, the overflowing bytes are actually part of the next packet. If the dlength value is bigger than the received data, then you must wait until the sender writes the rest of the data into the stream.