boost asio-更改有缺陷的代码
boost asio - change of deficient code
我有这段代码作为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()
,这将为异步处理调度完成处理程序。
相关文章:
- 需要以下代码的帮助,下面的代码有什么问题
- 在这个函数中是有缺陷的,因为取消引用 null 是无效的,所以我想更改代码
- 我关于函数"Assert"的C++代码有问题
- 为什么这两段使用 constexpr、__PRETTY_FUNCTION__ 和 char * 的代码有不同的结果?
- 以下 C++ 代码有什么问题?
- 当子类需要在 c++ 中相互包含时,继承有缺陷
- 继承此C++代码有什么问题
- 无法打印完整的二叉搜索树,因为我从最低节点向后迭代的逻辑有缺陷
- 有谁知道这段代码有什么问题?
- 我如何在一个 if 语句中声明所有数字我尝试通过其他方式声明所有数字,如果一个接一个,但似乎代码有逻辑错误
- 给定的两个代码有什么区别.一个在 ideone 上运行时超出时间限制,另一个工作正常
- 这段简单的代码有什么问题?
- 这个随机字符串打印代码有什么问题?
- 我在 c++ 中的 AES 代码有问题。明文正在更改,但加密邮件是相同的。我找不到我的错误
- 下面的代码有什么作用?c++
- 这两行代码有什么区别
- 我的C++合并排序代码有什么问题?
- 我的转置矩阵代码有什么问题?
- 尝试在C++中"blur"矩阵;有缺陷的算法或代码?
- boost asio-更改有缺陷的代码