C++ 在执行异步读取时,boost::asio::io\U服务异步写入循环
所以我的问题是,我有一个异步TCP服务器和相应的异步客户端。我需要的是一种能够(连续地)向客户机写入实时变量的方法,同时能够从客户机接收命令 我现在知道的是,如果客户机发送应该触发此操作的命令,它只发送一条测试消息,但我只找到了发送一条消息的方法,因为在此之后,服务器将挂起等待客户机命令 此函数用于处理从客户端发送的命令,并在接收后将其传递给函数h_read:C++ 在执行异步读取时,boost::asio::io\U服务异步写入循环,c++,boost-asio,tcpserver,C++,Boost Asio,Tcpserver,所以我的问题是,我有一个异步TCP服务器和相应的异步客户端。我需要的是一种能够(连续地)向客户机写入实时变量的方法,同时能够从客户机接收命令 我现在知道的是,如果客户机发送应该触发此操作的命令,它只发送一条测试消息,但我只找到了发送一条消息的方法,因为在此之后,服务器将挂起等待客户机命令 此函数用于处理从客户端发送的命令,并在接收后将其传递给函数h_read: void conn::h_write() { memset( data_, '\0', sizeof(char)*max_l
void conn::h_write() {
memset( data_, '\0', sizeof(char)*max_length );
async_read_until(sock_ , input_buffer_, '\n',
boost::bind(&conn::h_read, shared_from_this()));
}
在这里,我检查该命令是否应该触发将实时缓冲区连续写入客户端的命令,在这种情况下,该命令是“c”
问题是它在第一次调用“async\u read\u util”函数后阻塞
我甚至不知道我想要的是否可能,但如果可能的话,有人能帮我做吗
我需要的是一种能够(持续)给我的客户写信的方式,
一个实时变量,同时能够接收
来自客户端的命令
这不是问题
分离读写函数。成功连接/初始化套接字后调用一次。然后在读处理程序中再次调用它。没有别的地方。这是执行读取操作的常用方法
另请参阅
程序必须确保流不执行其他读取
操作(如async_read、async_read_until、流的
异步读取某个函数或任何其他组合操作
执行读取),直到此操作完成
请记住,读取缓冲区中的数据可能包含比您预期的更多的内容
在成功的异步读取操作之后,streambuf可能
包含分隔符之外的其他数据。申请将
通常将该数据保留在streambuf中以供后续处理
异步读取直到要检查的操作
void conn::h_read(){
std::string line;
std::istream is(&input_buffer_);
std::getline(is, line);
std::string output = "";
output.reserve(5000);
if ( line == "exit"){
return;
}
if ( line.empty() ){
memset( data_, '\0', sizeof(char)*max_length );
async_read_until(sock_ , input_buffer_, '\n', boost::bind(&conn::h_read, shared_from_this()));
return;
}
clientMessage_ = line;
clientMessage_ += '\n';
if ( clientMessage_.substr(0,1) == "c" ){
std::stringstream toSend;
streamON = true;
toSend.str("c l 1 ");
toSend << std::fixed << std::setprecision( 2 ) << luxID1[0];
toSend.str(" ");
// Here I sent the real time value for the first time
boost::asio::async_write(sock_, boost::asio::buffer( toSend.str() ), boost::bind(&conn::sendRealTime, shared_from_this()));
}
else{ // Does't really matter to this example
// Do some stuff here and send to client
boost::asio::async_write(sock_, boost::asio::buffer( I2CrxBuf_ ), boost::bind(&conn::h_write, shared_from_this()));
}
}
void conn::sendRealTime(){
if ( streamON ){
boost::asio::async_write(sock_, boost::asio::buffer( "This is a test\n" ), boost::bind(&conn::h_write, shared_from_this()));
memset( data_, '\0', sizeof(char)*max_length );
async_read_until(sock_ , input_buffer_, '\n', boost::bind(&conn::h_read, shared_from_this()));
}
else{
memset( data_, '\0', sizeof(char)*max_length );
async_read_until(sock_ , input_buffer_, '\n', boost::bind(&conn::h_read, shared_from_this()));
}
}