grivescorbett
grivescorbett

Reputation: 1625

Boost async_read

I'm trying to create a TCP server where the Start() method blocks until a connection is accepted, and then begins a series of asynchronous reads. I have the following code, and when I connect using telnet I get this output:

Waiting for a new connection

Connection accepted

terminate called throwing an exceptionAbort trap: 6

Here is the code:

void SocketReadThread::Start()
{
    bzero(m_headerBuffer, HEADER_LEN);
    m_running = true;

    asio::io_service ios;
    asio::ip::tcp::acceptor acp (ios,
        boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), GUI_PORT));

    asio::ip::tcp::socket sock(ios);
    std::cout << "Waiting for a new connection" << std::endl;

    acp.accept(sock); 
    std::cout << "Connection accepted" << std::endl;

    asio::async_read(sock, asio::buffer(m_headerBuffer, HEADER_LEN),
        boost::bind(&SocketReadThread::handleReadHeader, shared_from_this(),
        asio::placeholders::error));

    ios.run();
}

void SocketReadThread::handleReadHeader(const system::error_code& error)
{
    std::cout << "Read two bytes!" << std::endl;
}

Upvotes: 1

Views: 3951

Answers (2)

Andres Jaan Tack
Andres Jaan Tack

Reputation: 23014

You're probably doing something scary (and awesome) to the stack by declaring your ReadHandler incorrectly. Even if you ignore some parameters, the signature must be:

void handler (
  const boost::system::error_code& error, // Result of operation.

  std::size_t bytes_transferred           // Number of bytes copied into the
                                          // buffers. If an error occurred,
                                          // this will be the  number of
                                          // bytes successfully transferred
                                          // prior to the error.
);

Upvotes: 1

Abyx
Abyx

Reputation: 12918

You should wrap your main() function in try {...} catch (std::exception& e) { cout << e.what(); } block.

Upvotes: 2

Related Questions