Synchronization between send / recv in sockets

I have a server that sends data in the form of strings of various lengths (for example, 79.80.81.82)

I want to be able to receive exactly one record at a time. I split the records using (r), but because I don't know how many bytes I should get, Sometimes it combines the records and makes the process difficult for me.

+3
source share
4 answers

I have two ideas for you:

  • Use XML for the protocol. This way you know exactly when each message ends.
  • Send the packet size in the header of each "packet", so you know how much to read from the socket for this particular packet.

Edit: Look at this dummy code for (2)

int buffer_size;
char* buffer;

read( socket, &buffer_size, sizeof(buffer_size)); 
buffer = (char*) malloc(packet_size);
read( socket, buffer, buffer_size );
// do something
free( buffer) ; 

EDIT: , , "read()", "read()" ing, .

, . XML. , XML parlty, XML, , , 0 "" .

+4

?

, .

struct Message
{
  int dataSize;
  char data[256];
};
0

. , .

0

Stream sockets do not support the idea of ​​“recording” - the abstraction they provide is a continuous stream.

You must implement a layer on top of them to provide “records”. It looks like you have already gone there, with a separator for the end of the record. Pseudo code to complete it:

create empty buffer;
forever {
    recv data and append to buffer;

    while (buffer contains end-of-record marker) {
        remove first record from buffer and process it;
        move remaining data to beginning of buffer;
    }
}
0
source

Source: https://habr.com/ru/post/1763546/


All Articles