Debian Codegraph @

LspCpp/third_party/ixwebsocket/main.cpp

raw
1 /*
2 * main.cpp
3 * Author: Benjamin Sergeant
4 * Copyright (c) 2020 Machine Zone, Inc. All rights reserved.
5 *
6 * Super simple standalone example. See ws folder, unittest and doc/usage.md for more.
7 *
8 * On macOS
9 * $ mkdir -p build ; cd build ; cmake -DUSE_TLS=1 .. ; make -j ; make install
10 * $ clang++ --std=c++14 --stdlib=libc++ main.cpp -lixwebsocket -lz -framework Security -framework Foundation
11 * $ ./a.out
12 *
13 * Or use cmake -DBUILD_DEMO=ON option for other platform
14 */
15
16 #include <ixwebsocket/IXNetSystem.h>
17 #include <ixwebsocket/IXWebSocket.h>
18 #include <ixwebsocket/IXUserAgent.h>
19 #include <iostream>
20
21 int main()
22 {
23 // Required on Windows
24 ix::initNetSystem();
25
26 // Our websocket object
27 ix::WebSocket webSocket;
28
29 // Connect to a server with encryption
30 // See https://machinezone.github.io/IXWebSocket/usage/#tls-support-and-configuration
31 std::string url("wss://echo.websocket.org");
32 webSocket.setUrl(url);
33
34 std::cout << ix::userAgent() << std::endl;
35 std::cout << "Connecting to " << url << "..." << std::endl;
36
37 // Setup a callback to be fired (in a background thread, watch out for race conditions !)
38 // when a message or an event (open, close, error) is received
39 webSocket.setOnMessageCallback([](const ix::WebSocketMessagePtr& msg)
40 {
41 if (msg->type == ix::WebSocketMessageType::Message)
42 {
43 std::cout << "received message: " << msg->str << std::endl;
44 std::cout << "> " << std::flush;
45 }
46 else if (msg->type == ix::WebSocketMessageType::Open)
47 {
48 std::cout << "Connection established" << std::endl;
49 std::cout << "> " << std::flush;
50 }
51 else if (msg->type == ix::WebSocketMessageType::Error)
52 {
53 // Maybe SSL is not configured properly
54 std::cout << "Connection error: " << msg->errorInfo.reason << std::endl;
55 std::cout << "> " << std::flush;
56 }
57 }
58 );
59
60 // Now that our callback is setup, we can start our background thread and receive messages
61 webSocket.start();
62
63 // Send a message to the server (default to TEXT mode)
64 webSocket.send("hello world");
65
66 // Display a prompt
67 std::cout << "> " << std::flush;
68
69 std::string text;
70 // Read text from the console and send messages in text mode.
71 // Exit with Ctrl-D on Unix or Ctrl-Z on Windows.
72 while (std::getline(std::cin, text))
73 {
74 webSocket.send(text);
75 std::cout << "> " << std::flush;
76 }
77
78 return 0;
79 }