3

我正在编写 TCP 客户端,它应该能够同时发送和接收数据。你能告诉我应该如何调用async_send并且async_receive是单独的线程吗?

换句话说,如何调用

m_Socket.async_send(boost::asio::buffer(txBuf.c_str(), txBuf.length()+1),
    boost::bind(&TCPClient::sendingHandler, this, boost::asio::placeholders::error));

m_Socket.async_receive(boost::asio::buffer(rxBuf, maxBufLen),
    boost::bind(&TCPClient::sendingHandler, this, boost::asio::placeholders::error));

boost::thread receivingThread(boost::bind(...));
boost::thread sendingThread(boost::bind(...));

如果我在处理程序中调用async_sendasync_receive再次调用它会正常工作吗?我需要一个不定式循环来发送/接收数据。

4

1 回答 1

2

主要思想是——在递归里面发送和接收TCPClient::sendingHandler/receivingHandler2 io_service's.这io_service's在 2 个线程内被调用 -

boost::thread receivingThread(boost::bind(...));
boost::thread sendingThread(boost::bind(...));

这个想法在本教程中很明显。您必须调用和使用 2 个单独的唯一区别io_service's

另一种选择是 1io_service和多个线程调用io_service::run。但是你必须使用boost::asio::strand远线程安全:

boost::asio::strand* _strand = new boost::asio::strand(io);
//then use it in handlers
boost::asio::async_read(*socket, 
                    boost::asio::buffer(msg.data(), result.size),
                    (*_strand).wrap(
                    boost::bind(&ConnectionInterface::parsePacket, shared_from_this(), boost::asio::placeholders::error)));
于 2012-10-25T03:57:26.690 回答