c++ - C++ / ASIO / TCP / Socket / Response 有时/经常是空的,即使 do_write 被成功调用
问题描述
我有一个关于 asio 和 TCP 套接字的问题。
目前我正在使用async_read_until
直到有两个“\n\n”的序列。如果没有错误,我会做一些数据库工作并向客户端返回响应。这基本上是使用 asio 示例完成的。我的问题是:如果我遇到错误(asio::error_code& ec != null
),那么我如何确保我可以将答案写回给客户?因为如果我确实从错误条件中调用 do_write(...) ,则大约一半的响应不会到达客户端。
void do_read (some data) {
asio::async_read_until(socket_, buf_, "\n\n",
[this, self](const asio::error_code& ec, std::size_t bytes_transferred)
{
if(ec) {
do_write("This answer does not reach the client 50% of the time, sometimes more; sometimes less");
} else {
do_write("You did well my young apprentice! Always works");
}
});
}
void do_write(const std::string& response) {
asio::async_write(socket_, asio::buffer(response.c_str(), response.length()),
[this, self, response](std::error_code ec, std::size_t bytes_transferred) {
if (ec) {
// no error here whats-o-ever!
} else {
// OK: bytes_transferred == response.size()
}
}
}
当然我在这里做错了什么,但是什么?起初我认为这都是异步的,所以参数可能超出了范围。但是do_write
无论 ec == null 是什么都被调用,我什至使用逐字字符串对其进行测试,就像在这个例子中一样。
- Archlinux
- ASIO 1.18.1
- netcat 作为客户端
- 海合会 10.2.0
- 不使用升压
解决方案
推荐阅读
- unity3d - 从图像 URL 获取纹理时,图像中的文本出现锯齿状/像素化
- java - 有没有办法在 Java 中创建内存中的 mongo 服务器?
- c++ - 通过构造函数创建的所有对象都具有相同的向量
- react-dates - airbnb/react-dates 中未显示箭头(在移动屏幕中是,不在桌面中)
- windows - 如何从 CMD 执行添加到 WSL2 内的 $PATH 的二进制文件?
- python - 比较python中的两个列表元素
- r - 当字符串带有空格时,agrep 不起作用,用于字符串匹配
- sql - 每个组的本地最大值的 SQL 排序结果
- android - java.lang.NullPointerException:尝试插入到 Telephony.Sms.Conversations 时,Uri 不能为空
- mysql - 如何在 Django 模型中声明 JSON 字段?