通过Boost Asio进行套接字重用 [英] Socket reusing with boost asio

查看:84
本文介绍了通过Boost Asio进行套接字重用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用boost asio套接字,该套接字绑定到本地地址/端口组合.效果很好.不起作用的是,一旦套接字和应用程序停止并重新启动,便重新使用套接字.

I try to use a boost asio socket, bound to a local address/port combination. That works great. What doesn't work, is the re-using of the socket once the socket and application has been stopped and restarted.

    //
    // 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()调用的顺序正确吗?

What am I missing? Is the ordering of the open(), set_option() and bind() call correct?

推荐答案

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

The code looks fine. Try to use error_code to get the result of your set_option() call.

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

这篇关于通过Boost Asio进行套接字重用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆