c++ - 尝试使用协程读取数据时发生读/写访问冲突异常
问题描述
我正在使用独立的 asio 1.18.1,没有提升。我正在尝试创建一个使用 C++ 20 中的协程的客户端,因为它没有包含在示例中。不幸的是,我write access violation
在尝试使用async_read_until
.
如何根据示例中的服务器修复客户端的读写?
聊天客户端(问题在这里)
#include <cstdlib>
#include <deque>
#include <iostream>
#include <thread>
#include <string>
#include <asio.hpp>
using asio::ip::tcp;
using asio::awaitable;
using asio::co_spawn;
using asio::detached;
using asio::redirect_error;
using asio::use_awaitable;
std::deque<std::string> write_msgs_;
void stop(tcp::socket& socket)
{
socket.close();
}
awaitable<void> reader(tcp::socket& socket)
{
try
{
for (std::string read_msg;;)
{
std::size_t n = co_await asio::async_read_until(socket, asio::dynamic_buffer(read_msg, 1024), "\n", use_awaitable);
//room_.deliver(read_msg.substr(0, n));
read_msg.erase(0, n);
}
}
catch (std::exception&)
{
stop(socket);
}
}
awaitable<void> writer(tcp::socket& socket)
{
try
{
while (socket.is_open())
{
if (write_msgs_.empty())
{
asio::error_code ec;
//co_await timer_.async_wait(redirect_error(use_awaitable, ec));
}
else
{
co_await asio::async_write(socket, asio::buffer(write_msgs_.front()), use_awaitable);
write_msgs_.pop_front();
}
}
}
catch (std::exception&)
{
stop(socket);
}
}
awaitable<void> connect(tcp::socket socket, const tcp::endpoint& endpoint)
{
std::error_code ec;
co_await socket.async_connect(endpoint, redirect_error(use_awaitable, ec));
co_spawn(socket.get_executor(), [&] { return reader(socket); }, detached);
co_spawn(socket.get_executor(), [&] { return writer(socket); }, detached);
if (!ec)
{
std::cout << "Connected to " << endpoint << std::endl;
}
}
int main()
{
try
{
asio::io_context io_context(1);
tcp::endpoint endpoint(asio::ip::make_address("127.0.0.1"), 666);
tcp::socket socket(io_context);
co_spawn(io_context, connect(std::move(socket), endpoint), detached);
asio::signal_set signals(io_context, SIGINT, SIGTERM);
signals.async_wait([&](auto, auto) { io_context.stop(); });
io_context.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
聊天服务器(示例中的那个)
#include <cstdlib>
#include <deque>
#include <iostream>
#include <list>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <asio/awaitable.hpp>
#include <asio/detached.hpp>
#include <asio/co_spawn.hpp>
#include <asio/io_context.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/read_until.hpp>
#include <asio/redirect_error.hpp>
#include <asio/signal_set.hpp>
#include <asio/steady_timer.hpp>
#include <asio/use_awaitable.hpp>
#include <asio/write.hpp>
using asio::ip::tcp;
using asio::awaitable;
using asio::co_spawn;
using asio::detached;
using asio::redirect_error;
using asio::use_awaitable;
//----------------------------------------------------------------------
class chat_participant
{
public:
virtual ~chat_participant() = default;
virtual void deliver(const std::string& msg) = 0;
};
typedef std::shared_ptr<chat_participant> chat_participant_ptr;
//----------------------------------------------------------------------
class chat_room
{
public:
void join(chat_participant_ptr participant)
{
participants_.insert(participant);
for (const auto& msg : recent_msgs_)
participant->deliver(msg);
}
void leave(chat_participant_ptr participant)
{
participants_.erase(participant);
}
void deliver(const std::string& msg)
{
recent_msgs_.push_back(msg);
while (recent_msgs_.size() > max_recent_msgs)
recent_msgs_.pop_front();
for (const auto& participant : participants_)
participant->deliver(msg);
}
private:
std::set<chat_participant_ptr> participants_;
enum { max_recent_msgs = 100 };
std::deque<std::string> recent_msgs_;
};
//----------------------------------------------------------------------
class chat_session
: public chat_participant,
public std::enable_shared_from_this<chat_session>
{
public:
chat_session(tcp::socket socket, chat_room& room)
: socket_(std::move(socket)),
timer_(socket_.get_executor()),
room_(room)
{
timer_.expires_at(std::chrono::steady_clock::time_point::max());
}
void start()
{
room_.join(shared_from_this());
co_spawn(socket_.get_executor(),
[self = shared_from_this()]{ return self->reader(); },
detached);
co_spawn(socket_.get_executor(),
[self = shared_from_this()]{ return self->writer(); },
detached);
}
void deliver(const std::string& msg) override
{
write_msgs_.push_back(msg);
timer_.cancel_one();
}
private:
awaitable<void> reader()
{
try
{
for (std::string read_msg;;)
{
std::size_t n = co_await asio::async_read_until(socket_, asio::dynamic_buffer(read_msg, 1024), "\n", use_awaitable);
room_.deliver(read_msg.substr(0, n));
read_msg.erase(0, n);
}
}
catch (std::exception&)
{
stop();
}
}
awaitable<void> writer()
{
try
{
while (socket_.is_open())
{
if (write_msgs_.empty())
{
asio::error_code ec;
co_await timer_.async_wait(redirect_error(use_awaitable, ec));
}
else
{
co_await asio::async_write(socket_, asio::buffer(write_msgs_.front()), use_awaitable);
write_msgs_.pop_front();
}
}
}
catch (std::exception&)
{
stop();
}
}
void stop()
{
room_.leave(shared_from_this());
socket_.close();
timer_.cancel();
}
tcp::socket socket_;
asio::steady_timer timer_;
chat_room& room_;
std::deque<std::string> write_msgs_;
};
//----------------------------------------------------------------------
awaitable<void> listener(tcp::acceptor acceptor)
{
chat_room room;
for (;;)
{
std::make_shared<chat_session>(co_await acceptor.async_accept(use_awaitable), room)->start();
}
}
//----------------------------------------------------------------------
int main()
{
try
{
unsigned short port = 666;
asio::io_context io_context(1);
co_spawn(io_context,
listener(tcp::acceptor(io_context, { tcp::v4(), port })),
detached);
asio::signal_set signals(io_context, SIGINT, SIGTERM);
signals.async_wait([&](auto, auto) { io_context.stop(); });
io_context.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
解决方案
套接字被提前销毁。解决此问题的一种方法是:不要将套接字移动到连接功能中。以连接函数中的套接字为参考。这应该让您的插座寿命足够长。
推荐阅读
- xamarin - 为什么应用程序处于中断模式?
- msbuild - 禁用特定 MsBuild 项目的传递 PackageReference 依赖项
- deep-learning - Caffe 在微调训练 mean.binaryproto 上失败:Movidius
- r - ggplot2 带有断 Y 轴的条形图
- android - 如何将打字点添加到recyclerview
- sql - 没有结果集或更新/删除计数的 JPA / JPQL 查询
- javascript - 在使用 AngularJS 提交表单之前显示预览/编辑选项
- java - args 中不存在的参数
- java - 使用 Jersey 生成 JSON 和 XML 时,@XmlElement 并不总是有效
- django - Django,将 jpg 文件存储为 http POST 中的字符串