]> git.sesse.net Git - ultimatescore/blob - client/ws_server.cpp
914da3877e98fdfdfaeaa7d6b9014dedd24ef14c
[ultimatescore] / client / ws_server.cpp
1 #include "ws_server.h"
2
3 #include <functional>
4
5 #include <sys/types.h>
6 #include <sys/socket.h>
7 #include <netdb.h>
8 #include <unistd.h>
9 #include <errno.h>
10 #include <stdio.h>
11 #include <string.h>
12 #include <sys/ioctl.h>
13
14 #include "QtWebSockets/qwebsocketserver.h"
15 #include "QtWebSockets/qwebsocket.h"
16
17 using namespace std;
18
19 WSServer::WSServer(const string &host, int port)
20         : ws_server(new QWebSocketServer("ACMP client", QWebSocketServer::NonSecureMode, this))
21 {
22         if (ws_server->listen(QHostAddress::Any, port)) {
23                 connect(ws_server, &QWebSocketServer::newConnection, this, &WSServer::on_new_connection);
24         }
25 }
26
27 void WSServer::change_port(int port)
28 {
29         unordered_set<QWebSocket *> old_clients = move(clients);
30         for (QWebSocket *sock : old_clients) {
31                 delete sock;
32         }
33         ws_server->close();
34         ws_server->listen(QHostAddress::Any, port);
35 }
36
37 void WSServer::add_init_command(const string &cmd)
38 {
39         init_commands.push_back(cmd + "\r\n");
40 }
41
42 void WSServer::set_connection_callback(const std::function<void(bool)> &callback)
43 {
44         connection_callback = callback;
45 }
46
47 void WSServer::send_command(const string &cmd)
48 {
49         for (QWebSocket *sock : clients) {
50                 sock->sendTextMessage(QString::fromStdString(cmd));
51         }
52 }
53
54 void WSServer::on_new_connection()
55 {
56         QWebSocket *sock = ws_server->nextPendingConnection();
57         connect(sock, &QWebSocket::disconnected, this, &WSServer::disconnected);
58
59         for (const string &cmd : init_commands) {
60                 sock->sendTextMessage(QString::fromStdString(cmd));
61         }
62         clients.insert(sock);
63         connection_callback(true);
64 }
65
66 void WSServer::disconnected()
67 {
68         QWebSocket *sock = qobject_cast<QWebSocket *>(sender());
69         if (sock) {
70                 clients.erase(sock);
71                 sock->deleteLater();
72                 connection_callback(!clients.empty());
73         }
74 }