1 #include "ribbonserver.h"
2 #include "ribbonsocket.h"
4 #include <QtNetwork/QTcpServer>
5 #include <QtNetwork/QTcpSocket>
6 #include <QJsonDocument>
9 RibbonServer::RibbonServer(QObject* parent) :
12 server = new QTcpServer(this);
13 QObject::connect(server, SIGNAL(newConnection()),
14 this, SLOT(onNewConnection()));
17 RibbonServer::~RibbonServer()
21 bool RibbonServer::listen(const QHostAddress& address, quint16 port)
25 return server->listen(_addr, _port);
28 void RibbonServer::onNewConnection()
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) {
36 qDebug() << "Server closed";
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)));
44 void RibbonServer::onDisconnection(RibbonSocket* r)
47 qDebug() << "Socket disconnected:" << r->s();
49 if (!server->isListening()) {
50 server->listen(_addr, _port);
51 qDebug() << "Server listening on" << _addr << ":" << _port;
55 void RibbonServer::onMessageReceived(RibbonSocket* r, QByteArray buf)
57 qDebug() << "server: got data from" << r->s()->peerAddress() << r->s()->peerPort();
59 QJsonDocument json = QJsonDocument::fromJson(buf, &err);
61 qWarning() << "Json did not validate:" << err.errorString();
62 qWarning() << buf.constData();
63 qWarning() << "hexencoded:" << buf.toHex().constData();
66 qDebug() << "json document:" << json;