In my linux terminal I have the following 'conversation' that I want to run from qt using QTcpSocket:
S user@domain:~ $ netcat 1.1.1.2 9230
R HELO SOME MORE INFORMATION ABOUT THE DEVICE I CONNECTED TO
S DEVC 1.1.1.1 somePassword
R DEVC OK
S @AlarmCode=2,12
Where S is sended data and R is received data.
I made the following code, my header file:
#ifndef TCPCLIENT_H
#define TCPCLIENT_H
#include <QTcpSocket>
#include <QObject>
class TCPClient : public QObject
{
Q_OBJECT
private:
QTcpSocket *tcpSocket = nullptr;
void handleHeloMessage(QString message);
void handleConnectToDeviceMessage(QString message);
void handleMessage(QString message);
bool handledHeloMessage = false;
bool handledConnectToDeviceMessage = false;
void sendDeviceToConnectTo();
private slots:
void onConnected();
void handleReadyRead();
public:
TCPClient();
};
#endif // TCPCLIENT_H
My cpp:
#include "tcpclient.h"
#include <QDataStream>
#include <QDebug>
const QString COMMAND_RESET_ALARM = "@AlarmCode=1,-";
const QString COMMAND_CONNECT_TO_DEVICE = "DEVC 1.1.1.1 somePassword";
const QString IP_DATA_SOURCE = "1.1.1.2";
const int PORT_DATA_SOURCE = 9230;
#include <QDebug>
TCPClient::TCPClient()
{
tcpSocket = new QTcpSocket(this);
connect(tcpSocket, SIGNAL(connected()), this, SLOT(onConnected()));
connect(tcpSocket, SIGNAL(readyRead()), SLOT(handleReadyRead()));
tcpSocket->connectToHost(IP_DATA_SOURCE, PORT_DATA_SOURCE);
}
void TCPClient::handleHeloMessage(QString message)
{
if(message.left(4) == "HELO")
{
handledHeloMessage = true;
qDebug() << "Handled HELO \n" << message;
sendDeviceToConnectTo();
}
else{
qDebug() << "We did not receive halo but \n" << message;
}
}
void TCPClient::handleConnectToDeviceMessage(QString message)
{
qDebug() << "RECEIVED DEVICE\n" << message;
}
void TCPClient::handleMessage(QString message)
{
qDebug() << "We received data. "<< message;
}
void TCPClient::sendDeviceToConnectTo()
{
QByteArray br = COMMAND_CONNECT_TO_DEVICE.toUtf8();
tcpSocket->write(br);
qDebug() << "Sending: " << br;
}
void TCPClient::onConnected()
{
qDebug() << "we are now connected.";
}
void TCPClient::handleReadyRead()
{
QByteArray dataReceived = tcpSocket->readAll();
QString dataReceivedString = QString::fromStdString(dataReceived.toStdString());
if(!handledHeloMessage)
{
handleHeloMessage(dataReceivedString);
}
else if(!handledConnectToDeviceMessage)
{
handleConnectToDeviceMessage(dataReceivedString);
}
else{
handleMessage(dataReceivedString);
}
}
When I run my program I get:
we are now connected.
Handled HELO
"HELO SOME MORE INFORMATION ABOUT THE DEVICE I CONNECTED TO"
Sending: "DEVC 1.1.1.1 somePassword"
I was expecting to receive DEVC OK next but the above part is all I get.
Why dont I receive DEVC OK
like the example from the terminal?
I found the problem, the message was not written until a new line was entered.
adding \n
to the message did the job.