我最近决定使用boost::asio
作为我的套接字,但现在我遇到了一个问题:文档似乎缺乏。
我想要做的是写一个函数,它将发送一个包含以下结构的消息:
uint16_t
)的2个字节void*
)。该数据将根据操作码例如,如果操作码是1,可能定义为OPCODE_LOGIN,那么操作码后面的字节可能包含一个包含登录信息等的字符串。
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;
}
然而,这不会编译。关于写入调用,我收到了一个神秘的编译错误:
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 &,CompletionCondition,boost::system::error_code &)' being compiled
1> with
1> [
1> SyncWriteStream=boost::asio::ip::tcp::socket *,
1> ConstBufferSequence=boost::asio::mutable_buffers_1,
1> CompletionCondition=boost::asio::detail::transfer_all_t
1> ]
1> c:\users\josh\documents\visual studio 2010\projects\client\client\main.cpp(53) : see reference to function template instantiation 'size_t boost::asio::write<boost::asio::ip::tcp::socket*,boost::asio::mutable_buffers_ 1>(SyncWriteStream &,const ConstBufferSequence &)' being compiled
1> with
1> [
1> SyncWriteStream=boost::asio::ip::tcp::socket *,
1> ConstBufferSequence=boost::asio::mutable_buffers_1
1> ]
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
正如您所看到的,错误消息直接指向Boost的write.hpp
文件,而不是我自己的任何代码。我相信我在某种程度上错误地调用了write()
,但之后一个坚实的小时谷歌搜索和研究参考和示例(所有这些都使用另一个重载write()
或正在使用具有明确定义的大小/结构的数据),我无法确定我究竟做错了什么这里。
有人可以帮我调试这个编译错误吗?
答案 0 :(得分:14)
文档似乎缺乏
highest voted question中的boost-asio与文档有关,从那里开始: - )
有人可以帮我调试这个编译错误吗?
write()
自由函数expects作为第一个参数的引用类型。不是你的示例中的指针
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)));
// ^^^^ correct type now
// by the way, at this point, is it safe to delete fullData to prevent memory leaks?
return true;
}
此时,删除fullData是否安全可以防止内存泄漏?
是的,write() is
阻止通话。调用返回时,使用缓冲区完成。我强烈建议将此代码异常保护为安全,但如果您希望使用动态存储持续时间创建缓冲区,请考虑使用new
和boost::scoped_array
。