Reputation: 113
I am boost::asio, the messages and responses are all in the form of packed structs, and as the structs are packed I don't see a use of serialization here. I have seen similar questions and all advice serialization, but that is not what I am looking for. How can we pass and receive a objects of these structs over a tcp connection boost::asio? I am new to boost and just exploring it so a code example will be of much help. thanks in advance.
Example struct:
typedef struct {
MessageHeaderInComp MessageHeaderIn;
RequestHeaderComp RequestHeader;
uint32_t Username;
char Password[LEN_PASSWORD];
char Pad4[LEN_PAD4];
} __attribute__((packed)) UserLoginRequest;
Upvotes: 1
Views: 765
Reputation: 393134
If you mean that the "packed struct" is actually POD (so standard-layour and trivially constructible/destructible), in short bitwise serializable, then you could say that your struct is a buffer.
Indeed, you may decide that you don't need to copy into another buffer/representation and use the buffer. That's simple, just adapt your object as a buffer:
UserLoginRequest req;
write(socket_or_stream, boost::asio::buffer(&req, sizeof(req)));
read(socket_or_stream, boost::asio::buffer(&req, sizeof(req)));
To avoid doing the math I prefer to use array declaration:
UserLoginRequest req[1];
write(socket_or_stream, boost::asio::buffer(req));
read(socket_or_stream, boost::asio::buffer(req));
Of course on async streams or sockets the async_*
variants can be used as well (given that the lifetime of the buffer extends to completion of the operation as always).
Related, you can contiguous storage of POD types as a buffer:
std::vector<UserLoginRequest> massLogin(123); // weird, but just for demo
write(socket_or_stream, boost::asio::buffer(massLogin));
read(socket_or_stream, boost::asio::buffer(massLogin));
This kind of bitwise serialization is NOT PORTABLE. I'm assuming that you are well aware of this and don't mind.
Upvotes: 1