gpt4 book ai didi

c++ - Boost asio io_content 运行非阻塞

转载 作者:行者123 更新时间:2023-12-01 14:53:49 32 4
gpt4 key购买 nike

<分区>

目前我正在编写一个 C++ Websocket 客户端库,它被封装在一个 C# 库中。
我正在使用 Boost Beast 进行 websocket 连接。
现在我在握手完成时启动 async_read,这样 websocket 就不会断开连接。
问题是 io_content 阻塞线程,因此 C# 程序停止执行,直到 async_read 超时并且 io_content 返回。但我希望 C# 程序继续执行。
我试图在一个线程中执行连接函数,但问题是,C# 程序调用的下一个函数是写操作,它崩溃了,因为连接函数仍在连接...

库.cpp:

void OpenConnection(char* id)
{
std::cout << "Opening new connection..." << std::endl;
std::shared_ptr<Session> session = std::make_shared<Session>();
session->connect();
sessions.emplace(std::string(id), std::move(session));
}

session .cpp:

void Session::connect()
{
resolver.async_resolve(
"websocket_uri",
"443",
beast::bind_front_handler(
&Session::on_resolve,
shared_from_this()));
ioc.run();
}

on_resolve、on_connect、on_handshake...与此处相同:https://www.boost.org/doc/libs/1_70_0/libs/beast/example/websocket/client/async-ssl/websocket_client_async_ssl.cpp

除非on_handshake函数:

void Session::on_handshake(beast::error_code ec)
{
if (ec)
return fail(ec, "handshake");

ws.async_read(buffer, beast::bind_front_handler(&Session::on_read, shared_from_this()));
}

还有 on_read 函数:

void Session::on_read(beast::error_code ec, std::size_t bytes_transfered)
{
boost::ignore_unused(bytes_transfered);

if (ec)
return fail(ec, "read");

std::cout << "Got message" << std::endl;
onMessage(Message::parseMessage(beast::buffers_to_string(buffer.data())));
ws.async_read(buffer, beast::bind_front_handler(&Session::on_read, shared_from_this()));
}

还有 on_write 函数:

void Session::on_write(beast::error_code ec, std::size_t bytes_transfered)
{
boost::ignore_unused(bytes_transfered);

if (ec)
return fail(ec, "write");

queue.erase(queue.begin());

if (!queue.empty())
{
ws.async_write(net::buffer(queue.front()->toString()), beast::bind_front_handler(&Session::on_write, shared_from_this()));
}
}

C#程序(用于测试):

[DllImport(@"/data/cpp_projects/whatsapp_web_library/build/Debug/libWhatsApp_Web_Library.so")]
public static extern void OpenConnection(string id);
[DllImport(@"/data/cpp_projects/whatsapp_web_library/build/Debug/libWhatsApp_Web_Library.so")]
public static extern void CloseConnection(string id);
[DllImport(@"/data/cpp_projects/whatsapp_web_library/build/Debug/libWhatsApp_Web_Library.so")]
public static extern void GenerateQRCode(string id);

static void Main(string[] args)
{
string id = "test";
OpenConnection(id);
GenerateQRCode(id);
}

现在是我的问题,我该如何实现它?
我已经在这个问题上停留了 3 天了,并且慢慢地感到绝望。

已经谢谢了:)

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com