我正在尝试使用 boost 库制作 TCP/IP 客户端。这就是我设计程序的方式
->读取线程从服务器读取
-> 写线程发送命令
-> 解析从服务器读取的数据的函数
int main()
{
TCP_IP_Connection router;
router.Create_Socket();
boost::thread_group t;
t.create_thread(boost::bind(&TCP_IP_Connection::get_status,&router,'i'));
t.create_thread(boost::bind(&TCP_IP_Connection::readTCP,&router));
std::string reply="\nend of main()";
std::cout<<reply;
t.join_all();
return 0;
}
void TCP_IP_Connection::Create_Socket()
{
tcp::resolver resolver(_io);//resolve into TCP endpoint
tcp::resolver::query query(routerip,rport);
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
//list of endpoints
tcp::resolver::iterator end;
boost::asio::streambuf b;
_socket = new tcp::socket(_io); //create socket
boost::system::error_code error= boost::asio::error::host_not_found;
try
{
while (error && endpoint_iterator != end) //if error go to next endpoint
{
_socket->close();
_socket->connect(*endpoint_iterator++, error);
}
if(error)
throw boost::system::system_error(error);
//else the router is connected
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
}
void TCP_IP_Connection::get_status(char p)
{
try
{
if(p=='i')
_socket->send(boost::asio::buffer("llist\n\n"));
//sending command for input command
else
_socket->send(boost::asio::buffer(" sspo l1\n\n"));
//sending signal presence for output command
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
}
void TCP_IP_Connection::readTCP()
{
this->len=0;
boost::system::error_code error= boost::asio::error::host_not_found;
try
{ //loop reading all values from router
while(1)
{
//wait for reply??
_socket->async_read_some(boost::asio::buffer(this-
>reply,sizeof(this>reply)),boost::bind(&TCP_IP_Connection::dataProcess,this,
boost::asio::placeholders::error,boost::asio::placeholders::bytes_transferred));
_io.run();
if(error==boost::asio::error::eof) //connection closed by router
std::cout<<"connection closed by router";
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
}
void TCP_IP_Connection::dataProcess(const boost::system::error_code &er,size_t l)
{
if(!er)
{
if(l>0)
{
for(int i=0;i<l;i++)
{
this->data[i]=this->reply[i];
//if(data[i]="\n")
std::cout<<this->data[i];
}
}
}
}
当我运行代码时,我得到的只是服务器的响应,表明客户端已连接,而不是我发送的命令的响应。但是当我尝试调试时,我会根据需要得到完整的输出。我在线程或 TCP 读取缓冲区中做错了什么吗?