【问题标题】:Boost acceptor accepts two times per incomming connection and makes two threads?Boost 接受器每个传入连接接受两次并创建两个线程?
【发布时间】:2013-07-07 11:05:37
【问题描述】:

我正在使用 TCP 服务器,并且正在使用 boost 库来实现 tcp 和套接字功能。我也在使用 boost 进行线程化。服务器可以工作,但是当我将客户端连接到服务器时,服务器会创建两个线程而不是一个。在接受连接后,我有一个控制台打印,并且每个连接都会看到此打印行两次。对于每个连接,将使用处理连接的函数创建一个新线程。我创建了一个 GlobalControll 类来设置服务器并处理连接。我的问题是为什么每个连接创建两个线程?因为它应该在接受函数后等待新的连接。

Bellow 是我认为出现问题的构造函数。

GlobalControl::GlobalControl(){

cout << "Setting up a server with the default port (" << PORTNUMBER << ")" << endl;

// Protocol and port
 boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), PORTNUMBER);   

 // Create acceptor
 boost::asio::ip::tcp::acceptor acceptor(io_service, endpoint);   

 // Create socket
 boost::asio::ip::tcp::socket socket(io_service); 

 for(;;){

     // Create socket
     SmartSocket sock(new boost::asio::ip::tcp::socket(io_service));

     // Waiting for client
     acceptor.accept(*sock);
     cout << "Client connected" << endl;
     boost::thread t(InitHandler, sock); 
     Sleep(1);
 };  
};

每个线程运行的Inithandler函数是如下函数:

    // Global function that each thread wil run
    void InitHandler(SmartSocket sock){

    int result = -1;
    byte RecvData[DataGenerator::SHA256BYTESIZE];
    DataGenerator DatGen;

       try
       {
            bool pending = true;
            while(pending)
           {
            // Generate a new vector
            DatGen.GenerateInputData();

            // Send vector
            boost::asio::write(*sock, boost::asio::buffer(DatGen.digest, sizeof(DatGen.digest)));

            // Make sure that the RecvData variable is clear
            CleanData(RecvData, DataGenerator::SHA256BYTESIZE);

            // Recieve data back from client
            boost::asio::read(*sock, boost::asio::buffer(RecvData, DataGenerator::SHA256BYTESIZE));

            // Compare input vector with recieved data from client
            result = memcmp (DatGen.digest, RecvData, sizeof(DataGenerator::SHA256BYTESIZE));

            if(result != 0){
                cout << "Error found" << endl;
            };


        }
   }
           catch (std::exception& e){
         // std::cout << "Exception in thread: " << e.what() << std::endl;
       }
    };

如果有人可以帮助我或给我关于这个问题的提示,那就太好了!非常感谢。

【问题讨论】:

  • 所以“客户端已连接”会打印两次,即使您只连接一个客户端?
  • 感谢您的称赞,是的。所以 te for 循环每个连接进行两次迭代。
  • 刚刚用调试器检查,创建了两个线程。检查线程的 ID,它们是唯一的。
  • for 循环之外的套接字是什么?
  • 我建议使用 async_accept 并在某处调用 io_service.run()

标签: c++ multithreading tcp boost-asio


【解决方案1】:

发现问题。没有以正确的方式将客户端套接字连接到服务器套接字。服务器的代码(在这个线程中)不是问题。在客户端以一种奇怪的方式调用了两次连接函数。

解决了服务端socket后调用connect解决了这个问题,如下:(解决服务端socket的代码省略)。

    tcp::socket socket(io_service);
    socket.connect(*iterator);

感谢所有cmets。

【讨论】:

    猜你喜欢
    • 2021-07-25
    • 1970-01-01
    • 2017-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-24
    • 1970-01-01
    • 2011-09-13
    相关资源
    最近更新 更多