-
Notifications
You must be signed in to change notification settings - Fork 12
/
demo_basic_echo_server.cpp
50 lines (41 loc) · 1.45 KB
/
demo_basic_echo_server.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
Simple Echo Server that can handle one client at a time.
After running this demo, there will be a websockets server running
on port SERVER_PORT (default 8080), that server will accept connections
and will respond with "echo" messages for every received message (one
clinet at a time, no multiple connections).
The code:
1. Sets up a server
2. Accepts a client
3. While the client connected, wait for a message
4. if that message is text, send an echo. otherwise don't do anything
5. When the client is no longer available, close the connection and start from step 1.
*/
#define SERVER_PORT 8080
#include <tiny_websockets/client.hpp>
#include <tiny_websockets/server.hpp>
#include <iostream>
using namespace websockets;
int main() {
WebsocketsServer server;
server.listen(SERVER_PORT);
// while the server is alive
while(server.available()) {
// accept a client
WebsocketsClient client = server.accept();
std::cout << "Client connected" << std::endl;
while(client.available()) {
// get a message, if it is text, return an echo
auto message = client.readBlocking();
if(message.isText()) {
client.send("Echo: " + message.data());
std::cout << "Sending echo: " << message.data() << std::endl;
}
}
// close the connection
if(client.available() == false) {
std::cout << static_cast<int>(client.getCloseReason()) << std::endl;
}
client.close();
}
}