Created
May 15, 2018 03:28
-
-
Save carlosolmos/b57e7054189fd67d37eef947cef91de9 to your computer and use it in GitHub Desktop.
QT Socket Server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
The server extends QTcpServer | |
*/ | |
SocketServer::SocketServer(QObject *parent) : QTcpServer(parent) | |
{ | |
} | |
//Method to start listening for connections in a given port and range of remote addresses: | |
//QHostAddress::LocalHost only accepts connections from localhost | |
//QHostAddress::Any accepts connections from anywhere. | |
void SocketServer::startServer(int port) | |
{ | |
if(listen(QHostAddress::LocalHost, port)){ | |
qDebug() << "Server Started"; | |
}else{ | |
qDebug() << "Sever failed to start"; | |
} | |
} | |
//Handle a incomming connection from a new client. | |
void SocketServer::incomingConnection(qintptr handle) | |
{ | |
qDebug() << "SocketServer::Incomming connection"; | |
//Instantiate the client handler | |
ClientSocket * inputSocket = new ClientSocket(this); | |
//initialize the handler with the incomming socket. | |
inputSocket->setSocket(handle); | |
//connect to the handler's signal to pass data (optional) | |
connect(inputSocket,SIGNAL(newMessage(QByteArray)), | |
this, SLOT(incommingMessage(QByteArray)), Qt::QueuedConnection); | |
} | |
//slot to receive data from the client handler. | |
void SocketServer::incommingMessage(QByteArray data) | |
{ | |
//do something with the data. | |
} | |
/* | |
The client handler is a wrapper for a QTcpSocket | |
Extends QObject | |
*/ | |
ClientSocket::ClientSocket(QObject *parent) : QObject(parent){ | |
} | |
//initialize the handler with the incomming socket | |
void InputSocket::setSocket(int descriptor){ | |
//this is the real socket. | |
_socket = new QTcpSocket(this); | |
//Tap the socket signals with local methods. | |
connect(_socket, SIGNAL(connected()), this, SLOT(connected())); | |
connect(_socket, SIGNAL(disconnected()), this, SLOT(disconnected())); | |
connect(_socket, SIGNAL(readyRead()), this, SLOT(readyRead())); | |
connect(_socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError))); | |
//connect the sockeet to the incomming descriptor | |
_socket->setSocketDescriptor(descriptor); | |
} | |
//Receive data from the client socket | |
void InputSocket::readyRead() | |
{ | |
QByteArray data = _socket->readAll(); | |
//pass the data to the listeners | |
emit newMessage(data); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment