我想要一个有状态的通信,但不喜欢boost的echo服务器示例。我的套接字将准备永久阅读,每当它接收到新数据时,它将调用虚拟方法dataAvailable(string)
但是它可以随时做async_write
。boost asio有状态套接字接口
void connected(const boost::system::error_code &ec) {
_socket.async_read_some(boost::asio::buffer(_buffer, max_length),
boost::bind(&Session::handler_read, this, boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
//boost::asio::async_read(_socket, boost::asio::buffer(_buffer, max_length),
// boost::bind(&Session::handler_read, this, boost::asio::placeholders::error,
// boost::asio::placeholders::bytes_transferred));
std::cout << ">> Session::connected()" << std::endl;
}
void handler_read(const boost::system::error_code &ec, size_t bytes_transferred) {
if(ec) {
std::cout << ec.message() << std::endl;
} else {
//std::copy(_buffer, _buffer+bytes_transferred, data.begin());
std::string data(_buffer, _buffer+bytes_transferred);
std::cout << ">> Session[ " << id() << "]" << "::handler_read(): " <<
bytes_transferred << " " << data << std::endl;
boost::asio::async_write(_socket, boost::asio::buffer(_buffer, max_length),
boost::bind(&Session::handler_write, this,
boost::asio::placeholders::error));
_socket.async_read_some(boost::asio::buffer(_buffer, max_length),
boost::bind(&Session::handler_read, this, boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
//boost::asio::async_read(_socket, boost::asio::buffer(_buffer, max_length),
// boost::bind(&Session::handler_read, this,
// boost::asio::placeholders::error,
// boost::asio::placeholders::bytes_transferred));
//call dataAvailable(_buffer);
}
}
void handler_write(const boost::system::error_code &ec) {
if(ec) {
std::cout << ec.message() << std::endl;
} else {
_socket.async_read_some(boost::asio::buffer(_buffer, max_length),
boost::bind(&Session::handler_read, this, boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
//boost::asio::async_read(_socket, boost::asio::buffer(_buffer, max_length),
// boost::bind(&Session::handler_read, this,
// boost::asio::placeholders::error,
// boost::asio::placeholders::bytes_transferred));
}
}
- 这是实现好?因为多个线程可能会执行读取和写入操作。其中写操作是在矩阵
- 为什么它不工作(不Echo的接收到的字符串)某些细胞的更新用,当我使用的
async_read
代替async_read_some
- 在我的听力服务器,我无处调用
listen
方法。但仍然在工作。那么为什么有一种听法?以及何时使用? - 我想从客户端退出客户端套接字时收到通知。例如客户已关闭连接。我该怎么做 ?我的方式是读
read_handler
但这是唯一的方法吗? - 我有一个Session类,每个会话都有一个套接字。我在会话管理器中存储
Session*
集合。现在当我关闭一个套接字并delete
它会话变为空。它可能发生在vector
的中间。那么如何安全地删除那个会话?
你可以用[self contained reproduction](http://sscce.org/)来编辑你的问题,这样我们就可以看到它不起作用了吗?在你发布的代码片段中没有明显的错误。 –