10
I've recently decided to use boost::asio for my sockets, but now I'm running into a problem: documentation seems to be lacking.
What I want to do is write a function that will send a message consisting of the following structure:
- 2 bytes of an unsigned integer (
uint16_t) for an opcode all bytes - all bytes after that (a flexible amount) being any type of data (cast to
void*). This data will be operated upon based on the opcode
For example, if the opcode is 1, perhaps defined as OPCODE_LOGIN, then the bytes following the opcode could contain a string containing login information, etc.
bool sendMessage(tcp::socket* sock, uint16_t opcode, void* data)
{
void* fullData = malloc(sizeof(uint16_t) + sizeof(data));
memcpy(fullData, (void*)opcode, sizeof(opcode));
memcpy(&fullData + sizeof(uint16_t), data, sizeof(data));
boost::asio::write(sock, boost::asio::buffer(fullData, sizeof(fullData)));
// by the way, at this point, is it safe to delete fullData to prevent memory leaks?
return true;
}
This does not compile, however. I get a cryptic compilation error regarding the call to write:
1>------ Build started: Project: client, Configuration: Debug Win32 ------
1> main.cpp
1>c:\boost\boost_1_47\boost\asio\impl\write.hpp(46): error C2228: left of '.write_some' must have class/struct/union
1> type is 'boost::asio::basic_stream_socket<Protocol> '
1> with
1> [
1> Protocol=boost::asio::ip::tcp
1> ]
1> did you intend to use '->' instead?
1> c:\boost\boost_1_47\boost\asio\impl\write.hpp(59) : see reference to function template instantiation 'size_t boost::asio::write<SyncWriteStream,ConstBufferSequence,boost::asio::detail::transfer_all_t>(SyncWriteStream &,const ConstBufferSequence &,Completi