开发者

synchronizing between send/recv in sockets

I have a server thats sendin开发者_高级运维g out data records as strings of varying length(for eg, 79,80,81,82)

I want to be able to receive exactly one record at a time.I've delimited records with a (r) but because I dont know howmany bytes I have to receive, It sometimes merges records and makes it difficult for me to process.


I have two ideas for you:

  1. Use XML for the protocol. This way you know exactly when each message ends.
  2. Send in the header of each "packet" the packet size, this way you know how much to read from the socket for this specific 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: I recommend looking at the comments here, as they note that the contect might not be ready by a simple "read()", you need to keep "read()"ing, until you get the correct buffer size.

Also - you might not need to read the size. Basically you need to look for the ending top level tag of the XML. This can be done by parsing the whole XML, or parlty parsing the XML you get from the stream untill you have 0 nodes "open".


You should delimit with null byte. Show us your code, and we may be able to help you.


Stream sockets do not natively support an idea of a "record" - the abstraction they provide is that of a continuous stream.

You must implement a layer on top of them to provide "records". It sounds like you are already part way there, with the end-of-record delimiter. The pseudo-code to complete it is:

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;
    }
}


Are you sending your data as a stream?

You can send it as a structure which is easier to parse and retrieve the data from.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜