-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.cpp
233 lines (198 loc) · 7.26 KB
/
main.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
// This code is released as public domain.
// -- Markus Goetz
#include <QGuiApplication>
#include <QUdpSocket>
#include <QTimer>
#include <QTcpServer>
#include <QTcpSocket>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QAbstractTableModel>
#include <QMap>
#include <QJsonDocument>
#include <QJsonObject>
//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
class NodeList : public QAbstractListModel {
Q_OBJECT
public:
enum NodeDataRoles {
AddrRole = Qt::UserRole + 1,
ChatLogRole
};
NodeList() {
}
QHash<int, QByteArray> roleNames() const {
QHash<int, QByteArray> roles;
roles[AddrRole] = "addr";
roles[ChatLogRole] = "log";
return roles;
}
int rowCount(const QModelIndex &parent = QModelIndex()) const {
Q_UNUSED(parent);
return nodes.size();
}
int columnCount(const QModelIndex &parent = QModelIndex()) const {
Q_UNUSED(parent);
return 1;
}
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const {
QMap<QString,QString>::const_iterator i = nodes.begin();
i += index.row();
if (role == AddrRole)
return i.key();
else if (role == ChatLogRole)
return i.value();
else
return "";
}
public slots:
void nodeDiscoveredSlot(QHostAddress addr) {
if (!nodes.contains(addr.toString())) {
beginResetModel();
nodes.insert(addr.toString(), "");
endResetModel();
}
}
void chatMessageReceivedSlot(QHostAddress addr, QByteArray json) {
QJsonDocument jsonDocument = QJsonDocument::fromJson(json);
QString msg = jsonDocument.object().value("chat").toObject().value("message").toString();
appendLog(addr.toString(), "Remote", msg.simplified());
}
void appendLog(QString addr, QString who, QString s) {
beginResetModel();
nodes[addr] = nodes[addr] + "<" + who + "> "+ s + "\n";
endResetModel();
}
private:
QMap<QString, QString> nodes;
};
//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
class Discovery : public QObject {
Q_OBJECT
public:
Discovery() {
socket.bind(31337);
connect(&socket, &QUdpSocket::readyRead, this, &Discovery::datagramReceived);
sendHelloDatagram();
helloTimer.setInterval(30*1000);
connect(&helloTimer, &QTimer::timeout, this, &Discovery::sendHelloDatagram);
helloTimer.start();
}
public slots:
void sendHelloDatagram() {
QByteArray helloDatagram("QLocalChat Hello");
socket.writeDatagram(helloDatagram, QHostAddress::Broadcast, 31337);
}
void datagramReceived() {
qint64 datagramSize = socket.pendingDatagramSize();
QByteArray datagram;
datagram.resize(datagramSize);
QHostAddress addr;
socket.readDatagram(datagram.data(), datagramSize, &addr);
if (datagram.startsWith("QLocalChat Hello")) {
emit nodeDiscovered(addr);
}
}
signals:
void nodeDiscovered(QHostAddress addr);
private:
QUdpSocket socket;
QTimer helloTimer;
};
//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
class HttpHandler : public QObject {
Q_OBJECT
public:
HttpHandler(QTcpSocket *so)
: state(Connected), socket(so), contentLength(0)
{
socket->setParent(this);
connect(socket, &QTcpSocket::readyRead, this, &HttpHandler::readyReadSlot);
}
public slots:
void readyReadSlot() {
while (state != ReadingData && socket->canReadLine()) {
QByteArray line = socket->readLine().simplified();
if (state == Connected && (line == "POST /chat HTTP/1.0" || line == "POST /chat HTTP/1.1")) {
state = ReadingHeaders;
} else if (state == Connected) {
delete this;
return;
} else if (state == ReadingHeaders && line.length() > 0) {
if (line.startsWith("Content-Length:")) {
contentLength = line.mid(15).toInt();
}
state = ReadingHeaders;
} else if (state == ReadingHeaders && line.length() == 0) {
state = ReadingData;
// send reply
socket->write("HTTP/1.0 200 OK\r\n");
socket->write("Connection: close\r\n");
socket->write("\r\n");
}
}
if (state == ReadingData && socket->bytesAvailable()) {
if (socket->bytesAvailable() >= contentLength) {
QByteArray data = socket->readAll();
emit chatMessageReceived(socket->peerAddress(), data);
QObject::connect(socket, &QTcpSocket::disconnected, socket, &QTcpSocket::deleteLater);
socket->disconnectFromHost();
return;
}
}
}
signals:
void chatMessageReceived(QHostAddress, QByteArray);
private:
enum ConnectionState {Connected, ReadingHeaders,
ReadingData, Closed};
ConnectionState state;
QTcpSocket *socket;
int contentLength;
};
//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
class HttpServer : public QObject {
Q_OBJECT
public:
HttpServer() {
QObject::connect(&serverSocket,&QTcpServer::newConnection,
this, &HttpServer::incomingConnection);
serverSocket.listen(QHostAddress::Any, 31337);
}
public slots:
void incomingConnection() {
QTcpSocket *incomingSocket = serverSocket.nextPendingConnection();
HttpHandler *httpHandler = new HttpHandler(incomingSocket);
httpHandler->setParent(this);
// Just forward the received message as signal
QObject::connect(httpHandler, &HttpHandler::chatMessageReceived,
this, &HttpServer::chatMessageReceived);
}
signals:
void chatMessageReceived(QHostAddress, QByteArray);
private:
QTcpServer serverSocket;
};
//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
NodeList nodeList;
engine.rootContext()->setContextProperty("nodeList", &nodeList);
Discovery localChatDiscovery;
QObject::connect(&localChatDiscovery, &Discovery::nodeDiscovered,
&nodeList, &NodeList::nodeDiscoveredSlot);
HttpServer localChatHttpServer;
QObject::connect(&localChatHttpServer, &HttpServer::chatMessageReceived,
&nodeList, &NodeList::chatMessageReceivedSlot);
// QML loading
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
#include "main.moc"