Created
May 14, 2018 05:30
-
-
Save carlosolmos/286904d81e7d35709b2c384f865ebf8b to your computer and use it in GitHub Desktop.
QT. Socket Client.
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
/* | |
Connecting to a TCP socket server. | |
*/ | |
//Create the socket object. | |
QTcpSocket *socket = new QTcpSocket(this); | |
//tap into the socket signals with some local methods. | |
//status signals | |
connect(socket, SIGNAL(connected()), this, SLOT(connected())); | |
connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected())); | |
// I/O signals | |
connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead())); | |
connect(socket, SIGNAL(bytesWritten(qint64)), this, SLOT(bytesWritten(qint64))); | |
//error handling signal | |
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError))); | |
//connect to the server. | |
socket->connectToHost(hostIp, port); | |
//Wait for connection up to 3000 ms. Failed if timeout. | |
if(!socket->waitForConnected(3000)){ | |
qDebug() << "Error connecting: " << socket->errorString(); | |
emit connectionError(); | |
} | |
/* | |
Receive message. | |
*/ | |
void SocketClient::readyRead(){ | |
//get the data | |
QByteArray buffer = socket->readAll(); | |
//do something with the data | |
//... | |
} | |
/* | |
Send some data | |
*/ | |
qint64 SocketClient::sendData(QByteArray msg){ | |
qint64 bytesSent = socket->write(msg); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment