sockets - C++ , sending structs via tcp -
i try send , receive data via tcp. problem want send 2 structs in 1 tcp message, there way link struct together. like:
send(connected, struct1 + struct2, sizeof(struct1 + struct2), 0); recv_data = recv(connected, struct1 + struct2,sizeof( struct1 + struct2),0);
if not possible add signal byte @ beginning of message like:
send(connected, "0x01" + struct1, sizeof(struct1 + 1), 0); recv_data = recv(connected, struct1,sizeof(struct1),0);
you writev
, readv
functions, allow sending/receiving data multiple non-contiguous memory locations.
struct iovec data[2]; data[0].iov_base = vector1.data(); data[0].iov_len = vector1.length() * sizeof(vector1[0]); data[1].iov_base = vector2.data(); data[1].iov_len = vector2.length() * sizeof(vector2[0]); writev(socket, data, 2);
however @ receiving side need way know number of incoming elements can reserve enough space read into.
this work vectors of trivially-copyable objects, not std::vector<std::string>
.
you need define kind of properly-designed serialization format, not copy raw bytes vectors sockets.
if don't know how (and pseudo-code suggests don't) @ protocol buffers instead.
edit: ok, you're not talking vectors, despite saying "vectors" repeatedly. simple structs of trivial types can it:
struct iovec data[2]; data[0].iov_base = &struct1; data[0].iov_len = sizeof(struct1); data[1].iov_base = &struct2; data[1].iov_len = sizeof(struct2); writev(socket, data, 2);
but still shouldn't copying raw bytes to/from sockets. work if sending , receiving machines agree on sizes, alignments , endianness of data types. still safer , more correct use properly-designed serialization system protocol buffers. has been designed people understand how these things correctly , safely.
Comments
Post a Comment