当我读取和写入超过 100000 条消息时,我收到了以下handleRead()
函数异常。boost::asio::read()
terminate called after throwing an instance of
'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::system::system_error> >'
what(): asio.ssl error
实现如下
读取功能
void start()
{
boost::asio::async_read(_socket,
boost::asio::buffer(_messageHeader, 8),
_strand.wrap(
boost::bind(
handleRead,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred
)
)
);
}
void handleRead(const boost::system::error_code& e,
std::size_t bytesTransferred)
{
if (!e)
{
BOOST_STATIC_ASSERT( sizeof(MessageHeader) == 8 );
Message message;
message.header.fromString(
std::string(_messageHeader.data(),
sizeof(MessageHeader)
)
);
boost::asio::read(_socket,
boost::asio::buffer(_buffer, message.header.length));
message.body = std::string(_buffer.data(), message.header.length);
this->start();
}
else {
this->close();
}
}
实现消息队列以写入消息
void sendResponse(const Message& response)
{
std::string stringToSend(response.toString());
boost::system::error_code error;
boost::asio::ip::tcp::endpoint endpoint = socket().remote_endpoint(error);
if ( error ) {
this->close();
}
_strand.post(
boost::bind(
writeImpl,
shared_from_this(),
stringToSend
)
);
}
void writeImpl(const std::string &message)
{
_outbox.push_back( message );
if ( _outbox.size() > 1 ) {
return;
}
this->write();
}
void write()
{
const std::string& message = _outbox[0];
boost::asio::async_write(
_socket,
boost::asio::buffer( message.c_str(), message.size() ),
_strand.wrap(
boost::bind(
writeHandler,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred
)
)
);
}
void writeHandler(
const boost::system::error_code& e,
const size_t bytesTransferred
)
{
_outbox.pop_front();
if ( e ) {
this->close();
}
if ( !_outbox.empty() ) {
this->write();
}
}