-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathws.cpp
48 lines (38 loc) · 1.2 KB
/
ws.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
#include "stdafx.h"
#include "ws.h"
using websocketpp::lib::placeholders::_1;
using websocketpp::lib::placeholders::_2;
using websocketpp::lib::bind;
BroadcastServer::BroadcastServer() {
wss.init_asio();
// Log to a file rather than stdout.
log.open("ws-output.log");
wss.get_alog().set_ostream(&log);
wss.get_elog().set_ostream(&log);
// Print all output to stdout.
//wss.register_ostream(&std::cout);
wss.set_open_handler(bind(&BroadcastServer::onOpen, this, ::_1));
wss.set_close_handler(bind(&BroadcastServer::onClose, this, ::_1));
wss.set_message_handler(bind(&BroadcastServer::onMessage, this, ::_1, ::_2));
}
void BroadcastServer::onOpen(connectionHandle handle) {
connections.insert(handle);
}
void BroadcastServer::onClose(connectionHandle handle) {
connections.erase(handle);
}
void BroadcastServer::onMessage(connectionHandle hdl, message msg) {
for (auto connection : connections) {
wss.send(connection, msg);
}
}
void BroadcastServer::send(std::string msg) {
for (auto connection : connections) {
wss.send(connection, msg, websocketpp::frame::opcode::text);
}
}
void BroadcastServer::run(uint16_t port) {
wss.listen(port);
wss.start_accept();
wss.run();
}