diff --git a/main.cpp b/main.cpp index a86dbc1..2a23f84 100644 --- a/main.cpp +++ b/main.cpp @@ -21,7 +21,7 @@ using json = nlohmann::json; atomic run_loop(true); // Run thread loops atomic close_ws(false); // control websocket -atomic send_ws(false); // send message to WebSocket +atomic send_ws(false); // send message to WebSocket mutex guard; // to protect ws // For console exit keywords @@ -36,9 +36,8 @@ unordered_set reconnect_key({ "r", "reset", "reconnect", "restart" }); // For sending messages unordered_set message_key({ "res", "send", "response" }); - -// Write message to -string message; +// Message for send +string send_msg; void websocket(string uri) { @@ -46,39 +45,25 @@ void websocket(string uri) WebSocket::pointer ws = WebSocket::from_url(uri); if (ws == NULL) { - //console.error("WebSocket not connected: " + uri); - //console.info("Trying to reconnect in 5 sec.."); - // Animation in console // more info: https://stackoverflow.com/questions/8486181/how-to-make-a-loading-animation-in-console-application-written-in-c cout << console.get( - "Trying to reconnect in:", - { console.light_magenta, console.underline }) << " "; + "Trying to reconnect in:", + { console.light_magenta, console.underline }) + << " "; int wait_for = 5; - for (int i=0; isend(message); + ws->send(send_msg); send_ws = false; } - - if (close_ws == true) { + if (close_ws) { ws->close(); + close_ws = false; } } - close_ws = false; delete ws; //run_loop = false; } @@ -124,10 +108,6 @@ void keybord() string keyword; cin >> keyword; if (exit_key.find(keyword) != exit_key.end()) { - //{ - //const lock_guard lock(guard); - //ws->close(); - //} console.debug("Exit"); close_ws = true; run_loop = false; @@ -140,9 +120,30 @@ void keybord() if (message_key.find(keyword) != message_key.end()) { if (!send_ws) { + send_msg = ""; + char c; + cout << "Message: "; - cin >> message; + // To get raw input from user + // ref: https://stackoverflow.com/questions/53797121/how-to-read-raw-input-in-cpp + cin.get(c); // To skip first '\n' when enter 'res' + while (cin.get(c)) { + if (c == '\n') { + break; + } + send_msg.push_back(c); + } send_ws = true; + // Check if the message in JSON + try { + json j_complete = json::parse(send_msg); + console.info("\n<<< JSON Data:"); + cout << setw(4) << j_complete << endl; + } catch (const exception& e) { + cout + << console.get("\n<<< ", { console.light_blue }) + << send_msg << endl; + } } else { console.warn("WebSocket is busy..."); }