我正在尝试创建一个TCP服务器,其中Start()方法阻塞,直到接受连接,然后开始一系列异步读取。我有以下代码,当我使用telnet连接时,我得到了这个输出:
等待新连接
接受连接
终止调用抛出异常陷阱陷阱:6
以下是代码:
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;
}
答案 0 :(得分:2)
您应该将main()
功能包装在try {...} catch (std::exception& e) { cout << e.what(); }
区块中。
答案 1 :(得分:1)
你可能通过错误地声明你的ReadHandler而对堆栈做了一些可怕的(并且很棒)。即使您忽略某些参数,签名也必须是:
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.
);