我正在尝试将 boost::asio 用于我的新的小爱好项目,但我无法让服务器读取正确的数据。发送它工作正常,我用wireshark检查过,字节[0 0 0 4]后跟[5 0 0 0]被发送。但是在服务器端我收到 [16 -19 105 0] 这让我很困惑。
这是我发送它的方式,通过wireshark查看时工作完美:
boost::asio::io_service io;
tcp::resolver resolver(io);
tcp::resolver::query query("localhost", boost::lexical_cast<string>("40001"));
tcp::resolver::iterator endpoints = resolver.resolve(query);
tcp::socket socket(io);
boost::asio::connect(socket, endpoints);
header h(5);
header::storage data = h.store();
boost::asio::write(socket, boost::asio::buffer(&data[0], header::header_size()));
这是我的服务器类的精简版。使用正确的字节数调用 handle_read_header,但 headerbuffer 包含奇怪的值,[16 -19 105 0]。
class tcp_connection : public boost::enable_shared_from_this<tcp_connection>
{
public:
tcp_connection(boost::asio::io_service& io)
: _socket(io)
{
memset(&headerbuffer[0], 0, headerbuffer.size());
}
void start() {
_socket.async_read_some(boost::asio::buffer(&headerbuffer[0], header::header_size()), boost::bind(&tcp_connection::handle_read_header, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void handle_read_header(const boost::system::error_code& error, std::size_t numBytes) {
if(!error) {
BOOST_LOG_SEV(logger, loglvl::debug) <<"handle_read_header, " <<numBytes <<"/" <<header::header_size() <<" bytes";
if (numBytes == header::header_size()) {
std::stringstream ss;
for(u32 a = 0; a < numBytes; ++a) {
ss <<(int)headerbuffer[a] <<" ";
}
BOOST_LOG_SEV(logger, loglvl::debug) <<"header data: " <<ss.str();
mCurrentHeader.load(headerbuffer);
mRemaining = mCurrentHeader.size();
BOOST_LOG_SEV(logger, loglvl::debug) <<"got header with size " <<mCurrentHeader.size();
}
} else {
BOOST_LOG_SEV(logger, loglvl::debug) <<"error " <<error;
}
}
private:
header mCurrentHeader;
std::array<char, 128> headerbuffer;
boost::asio::ip::tcp::socket _socket;
};
(几乎)完整的代码可以在http://paste2.org/U97HHaH3找到