Skip to content

Instantly share code, notes, and snippets.

@Hakkadaikon
Created January 5, 2024 01:28
Show Gist options
  • Select an option

  • Save Hakkadaikon/54d14a9f11d8721a3c85e8af75ed0cb5 to your computer and use it in GitHub Desktop.

Select an option

Save Hakkadaikon/54d14a9f11d8721a3c85e8af75ed0cb5 to your computer and use it in GitHub Desktop.
libhv (c++ websocket library) sample
#include "hv/WebSocketClient.h"
#include <thread>
#include <cstdio>
using namespace hv;
inline void put_message(const char* str, const int size)
{
for (int ii = 0; ii < size; ii++) {
putc_unlocked(str[ii], stdout);
}
putc_unlocked('\n', stdout);
}
int main(int argc, char** argv)
{
WebSocketClient ws;
ws.onopen = []() {
printf("onopen\n");
};
ws.onmessage = [](const std::string& msg) {
//printf("onmessage: %.*s\n", (int)msg.size(), msg.data());
put_message(msg.data(), msg.size());
};
ws.onclose = []() {
printf("onclose\n");
};
// reconnect: 1,2,4,8,10,10,10...
reconn_setting_t reconn;
reconn_setting_init(&reconn);
reconn.min_delay = 1000;
reconn.max_delay = 10000;
reconn.delay_policy = 2;
ws.setReconnect(&reconn);
printf("connect...\n");
ws.open("wss://nos.lol:443");
std::this_thread::sleep_for(std::chrono::seconds(1));
if (!ws.isConnected()) {
printf("connect failed!\n");
return -1;
}
// nostr subscribe event
// ws.send("[\"REQ\", \"foo\", {\"kinds\":[1], \"limit\":100}]");
// ws.send("[\"close\", \"foo\"]");
std::string str;
while (std::getline(std::cin, str)) {
if (!ws.isConnected()) {
break;
}
if (str == "quit") {
ws.close();
break;
}
ws.send(str);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment