droidlistener.cpp Example File
xandos/src/droidlistener.cpp
#include "droidlistener.hpp"
#include <QDebug>
#include <QtNetwork/QTcpSocket>
#include <QtNetwork/QTcpServer>
droidlistener::droidlistener(QObject *parent)
: QObject(parent), m_port(9876)
{
m_server = new QTcpServer(this);
bool ok = connect(m_server, SIGNAL(newConnection()), this, SLOT(newConnection()));
Q_ASSERT(ok);
Q_UNUSED(ok);
}
droidlistener::~droidlistener()
{
if (m_socket) {
disconnected();
m_socket->deleteLater();
}
m_server->close();
m_server->deleteLater();
}
void droidlistener::listen()
{
qDebug() << "xandos: start listening for connections";
m_server->listen(QHostAddress::LocalHost, m_port);
}
void droidlistener::newConnection()
{
m_socket = m_server->nextPendingConnection();
if (m_socket->state() == QTcpSocket::ConnectedState) {
qDebug() << "xandos: New connection established.";
}
bool ok = connect(m_socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
Q_ASSERT(ok);
ok = connect(m_socket, SIGNAL(readyRead()), this, SLOT(readyRead()));
Q_ASSERT(ok);
Q_UNUSED(ok);
}
void droidlistener::readyRead()
{
QByteArray ba = m_socket->read(20);
Q_EMIT droidSelection(QString(ba));
}
void droidlistener::readyWrite(const int code)
{
if (m_socket && m_socket->state() == QTcpSocket::ConnectedState) {
m_socket->write(QByteArray::number(code));
m_socket->flush();
}
}
void droidlistener::disconnected()
{
qDebug() << "xandOs: disconnecting...";
disconnect(m_socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
disconnect(m_socket, SIGNAL(readyRead()), this, SLOT(readyRead()));
m_socket->close();
}