sockets - C++ send data size before sending data via TCP -
disclaimer: new , clear can.
i have variable "packet" size of data. know tcp streaming protocol - streams bytes, not packets.
now, tell client size of data read stream (which constitutes 1 of 'packets').
the data sending in std::string
format
if string called outstring
, how populate uint8 buff[4]
size of string needs read on client?
my client, written in c#, looks this:
int total = 0; int read; byte[] datasize = new byte[4]; read = socket.receive(datasize, 0, 4, 0); int size = bitconverter.toint32(datasize, 0); int dataleft = size; byte[] data = new byte[size]; while (total < size) { read = socket.receive(data, total, dataleft, 0); if (read == 0) { break; } total += read; dataleft -= read; }
apologies, isn't direct answer question, may useful.
programming raw sockets sucks. there's lot of work make program deal them robustly. example, in code snippet attempt receive 4 bytes datasize. there no guarantee that single socket.receive() operation read 4 bytes, can read between 1 , 4 bytes. have call socket.receive() in loop until have received 4 bytes, later.
fortunately there's things zeromq take of pain away , give nice simple message passing framework layered on top of sockets, pipes, memory, etc. if want done comes highly recommended.
Comments
Post a Comment