2011-12-08 140 views
2

我尝试使用升压asio套接字绑定到本地地址/端口组合。这很好。什么不起作用,是套接字和应用程序停止并重新启动后重新使用套接字。套接字重新使用升压asio

// 
    // open the socket - it would also be opened by the async_connect() 
    // method but we might need an open socket to bind it 
    _socket.open(boost::asio::ip::tcp::v4()); 

    if (_bindLocal) { 
     boost::asio::socket_base::reuse_address option(true); 
     _socket.set_option(option); 
     _socket.bind(_localEndpoint); 
    } 

    // Invoke async. connect. Immediate return, no throw. 
    _socket.async_connect(_remoteEndpoint, 
     boost::bind(&MyTransceiver::handleConnect, this, 
      boost::asio::placeholders::error)); 

我错过了什么? open(),set_option()和bind()调用的顺序是否正确?

回答

0

该代码看起来不错。尝试使用error_code来获取set_option()调用的结果。

boost::system::error_code ec; 
_socket.set_option(boost::asio::socket_base::reuse_address(true), ec); 
+1

我有错误代码,它是0。随后调用async_connect()抛出,该地址不能使用两次。就像set_option()不存在一样。 – PMiller

+0

我必须说,我在Windows和netstat输出说“等待”使用的套接字。 – PMiller

+0

你的意思是time_wait?这是正确的状态,这就是为什么你需要设置reuse_address来确定。也许你可以尝试使用winsock API setsockopt()直接将SO_REUSEADDR属性设置为底层套接字。 – Shawnone