boost asio-更改有缺陷的代码

boost asio - change of deficient code

本文关键字:代码 有缺陷 asio- boost      更新时间:2023-10-16

我有这段代码作为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套接字异常->并结束数据交换。

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