#include <QtNetwork/QTcpServer>
#include <QtNetwork/QTcpSocket>
+#include <QJsonDocument>
#include <QDebug>
RibbonServer::RibbonServer(QObject* parent) :
void RibbonServer::onMessageReceived(RibbonSocket* r, QByteArray buf)
{
qDebug() << "server: got data from" << r->s()->peerAddress() << r->s()->peerPort();
- qDebug() << " message was:" << buf.constData();
- // TODO: do something with the packet in buf.constData()
+ QJsonParseError err;
+ QJsonDocument json = QJsonDocument::fromJson(buf, &err);
+ if (json.isNull()) {
+ qWarning() << "Json did not validate:" << err.errorString();
+ qWarning() << buf.constData();
+ qWarning() << "hexencoded:" << buf.toHex().constData();
+ r->abort();
+ } else {
+ qDebug() << "json document:" << json;
+ }
}
#include "ribbonsocket.h"
-#include <QDebug>
RibbonSocket::RibbonSocket(QTcpSocket* sock, QObject* parent) :
QObject(parent),
socket(sock),
state(WANT_LENGTH),
- bytes_wanted(0)
+ bytes_wanted(0),
+ aborting(false)
{
QObject::connect(socket, SIGNAL(disconnected()),
this, SLOT(onDisconnect()));
QObject::connect(socket, SIGNAL(readyRead()),
this, SLOT(onReadyRead()));
+ // Take ownership of the socket
+ socket->setParent(this);
}
RibbonSocket::~RibbonSocket()
return socket;
}
+void RibbonSocket::abort()
+{
+ aborting = true;
+ socket->abort();
+}
+
void RibbonSocket::onDisconnect()
{
emit disconnected(this);
{
switch(state) {
case WANT_LENGTH:
- qDebug() << "Want length, buf size before read:" << buf.length();
if (readUntilBufHas(4)) {
// Slice 4 octets off as big-endian integer
QByteArray size_buf = buf.left(4);
// TODO: decide on a maximum acceptable packet length, to avoid
// arbitrarily large packet buffer
buf.reserve(bytes_wanted);
- qDebug() << "length:" << bytes_wanted;
+ qDebug() << "socket: got length:" << bytes_wanted;
state = WANT_DATA;
return true;
}
break;
case WANT_DATA:
- qDebug() << "Want data, buf size before read:" << buf.length();
if (readUntilBufHas(bytes_wanted)) {
QByteArray data = buf.left(bytes_wanted);
buf = buf.mid(bytes_wanted);
// Memory optimization: release the rest of the buffer
buf.squeeze();
- qDebug() << "data:" << buf;
emit messageReceived(this, data);
state = WANT_LENGTH;
return true;
*/
bool RibbonSocket::readUntilBufHas(int desired_buffer_length)
{
- int size_to_read = desired_buffer_length - buf.length();
- QByteArray tmp = socket->read(size_to_read);
- qDebug() << "read" << tmp.length() << "from socket";
- buf += tmp;
+ // If we're shutting down the socket, don't try to read more from it
+ if (!aborting) {
+ int size_to_read = desired_buffer_length - buf.length();
+ QByteArray tmp = socket->read(size_to_read);
+ buf += tmp;
+ }
return buf.length() >= desired_buffer_length;
}