#include <libwebsockets.h>
#include "src/libs/callback.h"
#include "src/libs/websocket_client.h"
class websocket : public websocket_client, public client_callback_t {
bool run_ = true;
public:
websocket() : websocket_client(this, "ws-feed.pro.coinbase.com") {}
[[nodiscard]] bool working() const noexcept { return run_; }
void on_connected() override {
lwsl_user("client connectedn");
std::string msg = R"({ "type": "subscribe", "product_ids": [ "ETH-USD", "ETH-EUR" ], "channels": [ "level2", "heartbeat", { "name": "ticker", "product_ids": [ "ETH-BTC", "ETH-USD" ] } ] })";
send(msg.data(), msg.size());
}
void on_disconnected() override {
lwsl_user("client disconnectedn");
}
void on_error(const char *msg, size_t len) override {
lwsl_user("client errorn");
}
void on_data(const char *data, size_t len, size_t remaining) override {
std::string msg(data, len);
lwsl_user("data from server: %sn", msg.c_str());
}
};
int main() {
lws_set_log_level(LLL_USER | LLL_ERR | LLL_WARN | LLL_NOTICE, nullptr);
websocket client;
client.connect();
while (client.working()) {
}
return 0;
}
源
main
函数中while循环的目的是什么?如果我删除它,程序就会出错。
@user2994219在评论中发现了这个问题。
当主函数退出时,我发现stop((函数内的内容导致了segfault。stop((函数是在~websocket_client((内部调用的。将stop((移到析构函数的开头以解决问题。
这允许程序在没有分段冲突的情况下干净地退出。