【问题标题】:boost asio - change of deficient codeboost asio - 缺陷代码的更改
【发布时间】:2012-01-31 05:13:35
【问题描述】:

我将这段代码作为 socks5 代理服务器实现的一部分。这是一旦服务器与代理客户端(代码 - socket_)和目标服务器(代码 clientSock_)建立通信套接字的部分,它会在一个套接字上发送数据并与另一个套接字上发送的数据进行交换。

我指定此交换已在服务器为代理客户端生成的线程中发生。

    std::size_t readable = 0;

    boost::asio::socket_base::bytes_readable command1(true);
    boost::asio::socket_base::bytes_readable command2(true);


    try 
    {
        while (1)
        {
            socket_->io_control(command1);
            clientSock_->io_control(command2);

            if ((readable = command1.get()) > 0)
            {
                transf = ba::read(*socket_, ba::buffer(data_,readable));
                ba::write(*clientSock_, ba::buffer(data_,transf));
                boost::this_thread::sleep(boost::posix_time::milliseconds(500));
            }

            if ((readable = command2.get()) > 0)
            {
                transf = ba::read(*clientSock_, ba::buffer(data_,readable));
                ba::write(*socket_, ba::buffer(data_,transf));
                boost::this_thread::sleep(boost::posix_time::milliseconds(500));
            }
        }
    }
    catch (std::exception& ex)
    {
        std::cerr << "Exception in thread while exchanging: " << ex.what() << "\n";
        return;
    }

这里的问题是循环中的 CPU 非常高。另外我不确定这里是否知道其中一个部分是否已关闭套接字的方法是捕获 boost 套接字异常 -> 并结束数据交换。

【问题讨论】:

    标签: c++ sockets network-programming boost-asio


    【解决方案1】:

    这个问题可以通过使用异步写/读函数来解决。基本上使用async_read_some()async_write() - 或这些类别中的其他异步函数。此外,为了使异步处理工作,必须在调用至少一个异步函数后调用io_service.run() - 这将为异步处理调度完成处理程序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-28
      • 1970-01-01
      • 2016-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多