简体   繁体   English

Boost asio中的TCP客户端

[英]TCP client in Boost asio

Im building a TCP client using Boost::asio Libs. 我使用Boost :: asio Libs构建TCP客户端。 My program has a write() thread that sends a command to the server 我的程序有一个write()线程,它向服务器发送一个命令

write(*_socket,boost::asio::buffer("sspi l1\n\n",sizeof("sspi l1\n\n")));

Then a read thread is started that reads from the buffer all the time, as there can be messages broadcasted from the server due to any other client 然后启动一个读取线程,它始终从缓冲区读取,因为由于任何其他客户端,可能会从服务器广播消息

void TCP_IP_Connection::readTCP()
{

size_t l=0;

 this->len=0;
boost::system::error_code error;


try
  {//loop reading all values from router
   while(1)
     {

      //wait for reply??


    l=_socket->read_some(boost::asio::buffer(this->reply,sizeof(this->reply)),error);
    if(error)
        throw boost::system::system_error(error);

    if(l>0)
    {

        this->dataProcess(l);

    }
    else
        boost::this_thread::sleep(boost::posix_time::milliseconds(5000));


      _io.run();

       if(error==boost::asio::error::eof) //connection closed by router
         std::cout<<"connection closed by router";

       _io.reset();

     }

   }

catch (std::exception& e)
 {
   std::cerr << e.what() << std::endl;
 }

}

This thread runs al time in a while(1) loop and is supposed to sleep when the received data length is less than zero. 该线程在while(1)循环中运行,并且当接收的数据长度小于零时应该休眠。 It reads all the data and calls the data parser function. 它读取所有数据并调用数​​据解析器函数。 After that the write thread is used to send another command, with read thread running. 之后,写线程用于发送另一个命令,并且读线程正在运行。 But instead of the required response the server sends back 但是服务器发回的不是所需的响应

  ? ""
ERROR: Unknown command

I tried using the wireshark. 我尝试使用wireshark。 I can see the command being send properly. 我可以看到正确发送的命令。 What can be mistake I'm doing here? 我在做什么可能是错误的?

sizeof("sspi l1\\n\\n") returns 10, but I can only count 9 characters in that string. sizeof(“sspi l1 \\ n \\ n”)返回10,但我只能计算该字符串中的9个字符。

Try this instead: 试试这个:

const std::string cmd("sspi l1\n\n");
write(*_socket,boost::asio::buffer(cmd, cmd.length()));

Or when you have it as a string it is enough to do 或者当你把它作为一个字符串时就足够了

const std::string cmd("sspi l1\n\n");
write(*_socket,boost::asio::buffer(cmd));

The second argument specifies a maximum length of the string to use. 第二个参数指定要使用的字符串的最大长度。 But since it is a constant string, the second argument is not strictly necessary. 但由于它是一个常量字符串,因此第二个参数并非绝对必要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM