2013-01-11 135 views
6

以下是我使用boost asio的套接字服務器的示例代碼。boost asio服務器掛起在調用關閉boost :: socket

此服務器將在端口10001上等待任何客戶端進行連接。當任何客戶端連接時,它將開始從該客戶端讀取線程並等待另一個客戶端。但是當我的客戶端斷開服務器套接字時,會發生什麼情況會在my_socket->close()調用中掛起。

如果新客戶端嘗試連接服務器崩潰。

我使用 G ++(Ubuntu的4.4.3-4ubuntu5.1)4.4.3

#include <ctime> 
#include <iostream> 
#include <string> 
#include <boost/asio.hpp> 
#include <sys/socket.h> 
#include <unistd.h> 
#include <string> 
#include <boost/bind.hpp> 
#include <boost/thread.hpp> 
#include <boost/date_time.hpp> 

using namespace std; 
using boost::asio::ip::tcp; 

void run(boost::shared_ptr<tcp::socket> my_socket) 
{ 
    while (1) 
    { 
     char buf[128]; 
     boost::system::error_code error; 

     size_t len = my_socket->read_some(boost::asio::buffer(buf, 128), error); 
     std::cout << "len : " << len << std::endl; 

     if (error == boost::asio::error::eof) 
     { 
      cout << "\t(boost::asio::error::eof)" << endl; 
      if (my_socket->is_open()) 
      { 
       boost::system::error_code ec; 
       cout << "\tSocket closing" << endl; 
       my_socket->shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); 
       cout << "\tShutdown " << ec.message() << endl; 
//    cout << "normal close : " << ::close(my_socket->native_handle()) << endl; 
       my_socket->close(ec); 
       cout << "\tSocket closed" << endl; 
      } 
      break; // Connection closed cleanly by peer. 
     } 
     else if (error) 
     { 
      std::cout << "Exception : " << error.message() << std::endl; 
      break; 
     } 
     else 
     { 
      for (unsigned int i = 0; i < len; i++) 
       printf("%02x ", buf[i] & 0xFF); 
      printf("\n"); 
     } 
    } 
} 

int main() 
{ 
    const int S = 1000; 
    vector<boost::shared_ptr<boost::thread> > arr_thr(S); 

    try 
    { 
     for (uint32_t i = 0;; i++) 
     { 
      boost::asio::io_service io_service; 

      tcp::endpoint endpoint(tcp::v6(), 10001); 

      boost::shared_ptr<tcp::socket> my_socket(new tcp::socket(io_service)); 
      tcp::endpoint end_type; 

      tcp::acceptor acceptor(io_service, endpoint); 

      std::cout << "before accept" << endl; 
      acceptor.accept(*my_socket, end_type); 

      std::cout << "connected... hdl : " << my_socket->native_handle() << std::endl; 

      boost::asio::ip::address addr = end_type.address(); 
      std::string sClientIp = addr.to_string(); 

      std::cout << "\tclient IP : " << sClientIp << std::endl; 
      arr_thr[i] = boost::shared_ptr<boost::thread>(new boost::thread(&run, my_socket)); 
     } 
    } catch (std::exception& e) 
    { 
     std::cerr << e.what() << std::endl; 
    } 

    return 0; 
} 

回答

10

後你在主開始循環再次開始run線程,銷燬和重新初始化當地io_service變量,套接字上的下一個事件仍然會承擔舊的io_service對象,導致您的崩潰。

您應該只使用io_service的一個實例。

此外,你應該看看它的boost :: ASIO提供,如async_acceptasync_read異步功能,例如見這個例子:http://www.boost.org/doc/libs/1_52_0/doc/html/boost_asio/example/chat/chat_server.cpp

+0

日Thnx威廉。單個io_service實例解決了我的問題... –