TCPLoopBackServer.cc 1.78 KB
Newer Older
1 2 3 4 5 6 7 8 9
/****************************************************************************
 *
 *   (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/

10 11 12

#include "TCPLoopBackServer.h"

Don Gagne's avatar
Don Gagne committed
13 14 15 16 17
/// @file
///     @brief Simple TCP loop back server
///
///     @author Don Gagne <don@thegagnes.com>

18 19 20
TCPLoopBackServer::TCPLoopBackServer(QHostAddress hostAddress, quint16 port) :
    _hostAddress(hostAddress),
    _port(port),
21
    _tcpSocket(nullptr)
22 23 24 25 26 27 28 29 30 31 32
{
    moveToThread(this);
    start(HighPriority);
}
    
void TCPLoopBackServer::run(void)
{
    // Start the server side
    _tcpServer = new QTcpServer(this);
    Q_CHECK_PTR(_tcpServer);

33
    bool connected = QObject::connect(_tcpServer, &QTcpServer::newConnection, this, &TCPLoopBackServer::_newConnection);
34
    Q_ASSERT(connected);
35
    Q_UNUSED(connected); // Fix initialized-but-not-referenced warning on release builds
36 37 38 39 40 41 42 43 44 45 46 47

    Q_ASSERT(_tcpServer->listen(_hostAddress, _port));

    // Fall into main event loop
    exec();
}

void TCPLoopBackServer::_newConnection(void)
{
    Q_ASSERT(_tcpServer);
    _tcpSocket = _tcpServer->nextPendingConnection();
    Q_ASSERT(_tcpSocket);
48
    bool connected = QObject::connect(_tcpSocket, &QIODevice::readyRead, this, &TCPLoopBackServer::_readBytes);
49
    Q_ASSERT(connected);
50
    Q_UNUSED(connected); // Fix initialized-but-not-referenced warning on release builds
51 52 53 54 55 56 57 58 59
}

void TCPLoopBackServer::_readBytes(void)
{
    Q_ASSERT(_tcpSocket);
    QByteArray bytesIn = _tcpSocket->read(_tcpSocket->bytesAvailable());
    Q_ASSERT(_tcpSocket->write(bytesIn) == bytesIn.count());
    Q_ASSERT(_tcpSocket->waitForBytesWritten(1000));
}