1

我使用 boost:asio 来处理套接字。但是我在使用函数时出错boost::asio::write,这里是我的代码:

tcp::socket socket_;

Server(boost::asio::io_service& io_service) :  socket_(io_service) {}

tcp::socket& socket()
{
    return socket_;
}

void Server::start()
{
    startReadPacket(10); // example, client sends 10 bytes packet
}

void Server::startReadPacket(int size_to_read)
{
    boost::asio::async_read(socket(), boost::asio::buffer(byteBuffer->GetBytes(), MAX_BUFFER_SIZE), boost::asio::transfer_at_least(size_to_read), boost::bind(&Server::handle_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}

void Server::handle_read(const boost::system::error_code& error, size_t bytes_transferred)
{
    unsigned char data[2] = { 0x01, 0x24}; //for example
    boost::asio::write(socket(), boost::asio::buffer(data, 2)); // this code throws exception below
}

错误:

>   NewServer.exe!boost::throw_exception<boost::system::system_error>(const boost::system::system_error & e)  Line 61 + 0x2e bytes  C++
    NewServer.exe!boost::asio::detail::do_throw_error(const boost::system::error_code & err, const char * location)  Line 38 + 0xd bytes    C++
    NewServer.exe!boost::asio::write<boost::asio::basic_stream_socket<boost::asio::ip::tcp,boost::asio::stream_socket_service<boost::asio::ip::tcp> >,boost::asio::mutable_buffers_1>(boost::asio::basic_stream_socket<boost::asio::ip::tcp,boost::asio::stream_socket_service<boost::asio::ip::tcp> > & s, const boost::asio::mutable_buffers_1 & buffers)  Line 62    C++
    NewServer.exe!Server::handle_read(const boost::system::error_code & error, unsigned int bytes_transferred)  Line 91 + 0x26 bytes    C++
4

1 回答 1

3

提供的示例代码中没有 TCP 连接调用。该错误可能来自尝试写入未连接的套接字。在服务器的情况下,accept需要一个。(如果套接字初始化发生在您未显示的某些代码中,请忽略这一点)。

async_read将异步调用(例如)与阻塞调用(例如 )混合使用是非常少见的write。选择异步或阻塞调用并且不要混合使用它们是一种很好的做法。

您不检查handle_read. 如果失败,async_read阻塞也很可能失败。阻塞将在失败时抛出异常。writehandle_readwrite

我建议研究 asio 文档中的示例。

于 2012-12-28T20:54:47.577 回答