socket.cpp 2.55 KB
Newer Older
1 2 3 4 5 6 7 8

#include "socket.h"
#include "QtWebSockets/qwebsocketserver.h"
#include "QtWebSockets/qwebsocket.h"
#include <QtCore/QDebug>

QT_USE_NAMESPACE

9
Socket::Socket(quint16 port, QObject *parent) : QObject(parent),
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
    m_pWebSocketServer(new QWebSocketServer(QStringLiteral("Babe Server"),
                                            QWebSocketServer::NonSecureMode, this))
{
    if (this->m_pWebSocketServer->listen(QHostAddress::Any, port))
    {
        qDebug() << "Babe listening on port" << port;
        connect(this->m_pWebSocketServer, &QWebSocketServer::newConnection,
                this, &Socket::onNewConnection);
        connect(this->m_pWebSocketServer, &QWebSocketServer::closed, this, &Socket::closed);
    }
}

Socket::~Socket()
{
    m_pWebSocketServer->close();
    qDeleteAll(m_clients.begin(), m_clients.end());
}

void Socket::sendMessageTo(const int &client, const QString &message)
{
    if(this->m_clients.isEmpty() && this->m_clients.size()>=client)
        return;

    auto s_client = this->m_clients.at(client);
    s_client->sendTextMessage(message);
}

37 38 39 40 41 42 43 44 45 46
void Socket::sendArray(const int &client, const QByteArray &array)
{
    if(this->m_clients.isEmpty() && this->m_clients.size()>=client)
        return;

    auto s_client = this->m_clients.at(client);
    s_client->sendBinaryMessage(array);
    qDebug()<<"Array sent to client";
}

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
void Socket::onNewConnection()
{
    QWebSocket *pSocket = m_pWebSocketServer->nextPendingConnection();

    connect(pSocket, &QWebSocket::textMessageReceived, this, &Socket::processTextMessage);
    connect(pSocket, &QWebSocket::binaryMessageReceived, this, &Socket::processBinaryMessage);
    connect(pSocket, &QWebSocket::disconnected, this, &Socket::socketDisconnected);

    m_clients << pSocket;

    emit this->connected(m_clients.size()-1);
}

void Socket::processTextMessage(const QString &message)
{
    emit this->message(message);
63
//    QWebSocket *pClient = qobject_cast<QWebSocket *>(sender());
64

65 66 67 68
//    if (pClient)
//    {
//        pClient->sendTextMessage(message);
//    }
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
}

void Socket::processBinaryMessage(QByteArray message)
{
    QWebSocket *pClient = qobject_cast<QWebSocket *>(sender());

    qDebug() << "Binary Message received:" << message;
    if (pClient) {
        pClient->sendBinaryMessage(message);
    }
}

void Socket::socketDisconnected()
{
    QWebSocket *pClient = qobject_cast<QWebSocket *>(sender());

    qDebug() << "socketDisconnected:" << pClient;
    if (pClient) {
        emit this->disconnected(pClient->origin());
        m_clients.removeAll(pClient);
        pClient->deleteLater();
    }
}