gpt4 book ai didi

c++ - websocket计时器滴答后 boost asio短读错误

转载 作者:行者123 更新时间:2023-12-02 10:23:06 25 4
gpt4 key购买 nike

我正在尝试使用websocketpp连接到安全的websocket,但是在计时器的第二个滴答声后出现此奇怪的错误:

[2019-12-05 10:48:55] [info] asio async_read_at_least error: asio.ssl:335544539 (short read)
[2019-12-05 10:48:55] [error] handle_read_frame error: websocketpp.transport:11 (Generic TLS related error)
[2019-12-05 10:48:55] [info] asio async_write error: asio.ssl:336396495 (protocol is shutdown)
[2019-12-05 10:48:55] [fatal] handle_write_frame error: websocketpp.transport:2 (Underlying Transport Error)
[2019-12-05 10:48:55] [info] asio async_shutdown error: asio.ssl:335544539 (short read)
close handler: Underlying Transport Error
[2019-12-05 10:48:55] [disconnect] Disconnect close local:[1006,Underlying Transport Error] remote:[1000]

我的代码是:
#define _WEBSOCKETPP_CPP11_STL_
# ifdef _WIN32
# pragma warning(disable: 4503)
# pragma warning(disable: 4996)
# endif
# include <websocketpp/config/asio_client.hpp>
# include <websocketpp/client.hpp>
# include <websocketpp/frame.hpp>
#undef _WEBSOCKETPP_CPP11_STL_

#include <iostream>

using WSClient = websocketpp::client<websocketpp::config::asio_tls_client>;

int main()
{
WSClient client;

client.init_asio();

client.set_tls_init_handler([](auto)
{
auto result = websocketpp::lib::make_shared<boost::asio::ssl::context>(boost::asio::ssl::context::sslv23_client);

result->set_verify_mode(boost::asio::ssl::verify_none);

return result;
});

client.set_open_handler([&client](auto hdl)
{
client.set_timer(40000, [hdl, &client](auto)
{
if (auto con = client.get_con_from_hdl(hdl)) {
con->send(std::string(R"({"op":1,"d":1})"), websocketpp::frame::opcode::text);
}
});
});

client.set_close_handler([&client](auto hdl)
{
auto con = client.get_con_from_hdl(hdl);
std::cout << "close handler: " << con->get_ec().message() << std::endl;
});

client.set_fail_handler([&client](auto hdl)
{
auto con = client.get_con_from_hdl(hdl);
std::cout << "fail handler: " << con->get_ec().message() << std::endl;
});

websocketpp::lib::error_code ec;

const auto websocketUrl = "wss://gateway.discord.gg/?encoding=json&v=6";

auto con = client.get_connection(websocketUrl, ec);

if (ec) {
std::cout << "Could not create WebSocket connection because " << ec.message() << std::endl;
return 0;
}

client.connect(con);
client.run();
}

令人惊讶的是,如果我使用NodeJS进行相同的操作,则可以使用以下命令正常工作:
const WebSocket = require('ws');

let websocketUrl = 'wss://gateway.discord.gg/?encoding=json&v=6'

const ws = new WebSocket(websocketUrl);

ws.on('open', function() {
setInterval(() => {
console.log('ping');

ws.send('{"op":1,"d":1}');
}, 40000);
});

ws.on('error', function(e, v){
console.log('error', e, v);
});

ws.on('unexpected-response', function(e, t, v){
console.log('unexpected-response', e, t);
});

ws.on('close', function() {
console.log('connection closed');
});

在C++版本中我在做什么错?

信封:Windows 10,MSVC 14,Websocketpp 0.8.1,Boost 1.69

最佳答案

根据文档[1],客户端必须发送ping(手册称它们为心跳):

Heartbeat:

Used to maintain an active gateway connection. Must be sent every heartbeat_interval milliseconds after the Opcode 10 Hello payload is received. The inner d key is the last sequence number—s—received by the client. If you have not yet received one, send null.


您正在使用WSClient::set_timer()(在set_open方法中)在C++实现中发送ping消息。但是,WSClient::set_timer()仅调用一次ping函数(您可以使用printf进行检查或阅读该方法的文档)。因此,您只发送一个ping消息。因此,从服务器上断开连接后,您的连接将被终止。
相反,您在NodeJS实现中使用“setIntervall()”来设置定期计时器。因此,将定期调用此计时器,并且服务器会定期接收您的ping消息。
我做了以下工作来修复您的C++代码[答案结尾处用于复制粘贴的完整代码]:
1.)添加处理程序以读取传入消息以进行调试:
client.set_message_handler([&client](auto hdl, auto msg_ptr)
{
std::string message = msg_ptr->get_payload();
std::cout << "received message: " << message << std::endl;
});
2.)以非阻塞方式启动websocket:
auto run_thread = std::thread{[&client](){client.run();}}; 
while(! client_is_open) { //this variable is defined elsewhere, see full code
sleep(1); //TODO: use an mutex instead
}
3.)执行ping操作:
int heartbeat_interval = 41250; //in ms: TODO extract from message
while(true) {
std::this_thread::sleep_for(std::chrono::milliseconds(heartbeat_interval));
client.send(con, "{\"op\":1, \"d\":null}", websocketpp::frame::opcode::text);
}
请注意以下事项:
  • 您必须从第一条消息中提取ping间隔。 (我没有)
  • ping消息应发送上次ping的序列号(请参阅相关文档)。我没有,它仍然有效,但是不要指望它。
  • client.run()是一个阻止调用,对此存在一些问题。

  • 您可以在下面找到我的代码
    [1] https://github.com/discordapp/discord-api-docs/blob/master/docs/topics/Gateway.md#DOCS_TOPICS_GATEWAY/heartbeat
    #define _WEBSOCKETPP_CPP11_STL_
    # ifdef _WIN32
    # pragma warning(disable: 4503)
    # pragma warning(disable: 4996)
    # endif
    # define _WEBSOCKETPP_CPP11_STL_
    # include <websocketpp/config/asio_client.hpp>
    # include <websocketpp/client.hpp>
    # include <websocketpp/frame.hpp>
    #undef _WEBSOCKETPP_CPP11_STL_

    #include <iostream>

    using WSClient = websocketpp::client<websocketpp::config::asio_tls_client>;;

    int main() { WSClient client;

    client.init_asio();
    bool client_is_open = false;

    client.set_tls_init_handler([](auto)
    {
    auto result = websocketpp::lib::make_shared<boost::asio::ssl::context>(boost::asio::ssl::context::sslv23_client);

    result->set_verify_mode(boost::asio::ssl::verify_none);

    return result;
    });

    client.set_open_handler([&client,&client_is_open](auto hdl)
    {
    client_is_open=true;
    });

    client.set_close_handler([&client](auto hdl)
    {
    auto con = client.get_con_from_hdl(hdl);
    std::cout << "close handler: " << con->get_ec().message() << std::endl;
    });

    client.set_fail_handler([&client](auto hdl)
    {
    auto con = client.get_con_from_hdl(hdl);
    std::cout << "fail handler: " << con->get_ec().message() << std::endl;
    });

    client.set_message_handler([&client](auto hdl, auto msg_ptr)
    {
    std::string message = msg_ptr->get_payload();
    std::cout << "received message: " << message << std::endl;
    });

    websocketpp::lib::error_code ec;

    const auto websocketUrl = "wss://gateway.discord.gg/?encoding=json&v=6";

    auto con = client.get_connection(websocketUrl, ec);

    if (ec) {
    std::cout << "Could not create WebSocket connection because " << ec.message() << std::endl;
    return 0;
    }

    client.connect(con);
    auto run_thread = std::thread{[&client](){client.run();}};
    while(! client_is_open) {
    sleep(1); //TODO: use an mutex instead
    }
    int heartbeat_interval = 41250; //in ms: TODO extract from message
    while(true) {
    std::this_thread::sleep_for(std::chrono::milliseconds(heartbeat_interval));
    client.send(con, "{\"op\":1, \"d\":null}", websocketpp::frame::opcode::text);
    }
    run_thread.join();

    }

    关于c++ - websocket计时器滴答后 boost asio短读错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59201960/

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