Boris
Boris

Reputation: 369

Error when boost::asio::write

I use boost:asio to handle sockets. But i have error when use boost::asio::write funcion, here my code:

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
}

Error:

>   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++

Upvotes: 1

Views: 2377

Answers (1)

jcm
jcm

Reputation: 977

There is no TCP connection call in the sample code provided. The error could come from trying to write to an unconnected socket. In the case of a server, an accept is needed. (Please ignore this in case the socket initialisation happens in some code you didn't show).

It's very uncommon to mix asynchronous calls (eg. async_read) with blocking calls (eg. write). It's good practice to choose either asynchronous or blocking calls and don't mix them.

You don't check the error code in handle_read. If the async_read fails, the blocking write in handle_read is very likely to fail as well. The blocking write will throw an exception on failure.

I would recommend to study the examples in the asio documentation.

Upvotes: 3

Related Questions