Created
January 5, 2024 01:28
-
-
Save Hakkadaikon/54d14a9f11d8721a3c85e8af75ed0cb5 to your computer and use it in GitHub Desktop.
libhv (c++ websocket library) sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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