]> git.sesse.net Git - ultimatescore/blob - client/ws_server.cpp
Make the roster scripts executable.
[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::set_connection_callback(const std::function<void(bool)> &callback)
38 {
39         connection_callback = callback;
40 }
41
42 void WSServer::send_command(const string &cmd)
43 {
44         for (QWebSocket *sock : clients) {
45                 sock->sendTextMessage(QString::fromStdString(cmd));
46         }
47 }
48
49 void WSServer::on_new_connection()
50 {
51         QWebSocket *sock = ws_server->nextPendingConnection();
52         connect(sock, &QWebSocket::disconnected, this, &WSServer::disconnected);
53
54         clients.insert(sock);
55         connection_callback(true);
56 }
57
58 void WSServer::disconnected()
59 {
60         QWebSocket *sock = qobject_cast<QWebSocket *>(sender());
61         if (sock) {
62                 clients.erase(sock);
63                 sock->deleteLater();
64                 connection_callback(!clients.empty());
65         }
66 }