]> git.zarvox.org Git - imoo.git/blob - ribbon/ribbonserver.cpp
1c8e3a80cbc295bcefda4088991f0589b527b194
[imoo.git] / ribbon / ribbonserver.cpp
1 #include "ribbonserver.h"
2 #include "ribbonsocket.h"
3
4 #include <QtNetwork/QTcpServer>
5 #include <QtNetwork/QTcpSocket>
6 #include <QJsonDocument>
7 #include <QDebug>
8
9 RibbonServer::RibbonServer(QObject* parent) :
10         QObject(parent)
11 {
12         server = new QTcpServer(this);
13         QObject::connect(server, SIGNAL(newConnection()),
14                         this, SLOT(onNewConnection()));
15 }
16
17 RibbonServer::~RibbonServer()
18 {
19 }
20
21 bool RibbonServer::listen(const QHostAddress& address, quint16 port)
22 {
23         _addr = address;
24         _port = port;
25         return server->listen(_addr, _port);
26 }
27
28 void RibbonServer::onNewConnection()
29 {
30         QTcpSocket* sock = server->nextPendingConnection();
31         qDebug() << "Accepted connection from" << sock->peerAddress() << ":" << sock->peerPort();
32         RibbonSocket* rsock = new RibbonSocket(sock, this);
33         sockets.append(rsock);
34         if (sockets.length() >= 1) {
35                 server->close();
36                 qDebug() << "Server closed";
37         }
38         QObject::connect(rsock, SIGNAL(disconnected(RibbonSocket*)),
39                         this, SLOT(onDisconnection(RibbonSocket*)));
40         QObject::connect(rsock, SIGNAL(messageReceived(RibbonSocket*,QByteArray)),
41                         this, SLOT(onMessageReceived(RibbonSocket*,QByteArray)));
42 }
43
44 void RibbonServer::onDisconnection(RibbonSocket* r)
45 {
46         sockets.removeOne(r);
47         qDebug() << "Socket disconnected:" << r->s();
48         r->deleteLater();
49         if (!server->isListening()) {
50                 server->listen(_addr, _port);
51                 qDebug() << "Server listening on" << _addr << ":" << _port;
52         }
53 }
54
55 void RibbonServer::onMessageReceived(RibbonSocket* r, QByteArray buf)
56 {
57         qDebug() << "server: got data from" << r->s()->peerAddress() << r->s()->peerPort();
58         QJsonParseError err;
59         QJsonDocument json = QJsonDocument::fromJson(buf, &err);
60         if (json.isNull()) {
61                 qWarning() << "Json did not validate:" << err.errorString();
62                 qWarning() << buf.constData();
63                 qWarning() << "hexencoded:" << buf.toHex().constData();
64                 r->abort();
65         } else {
66                 qDebug() << "json document:" << json;
67         }
68 }