QTcpSocket 模拟 netcat 'conversation'

QTcpSocket emulate netcat 'conversation'

在我的 linux 终端中,我有以下 'conversation' 我想使用 QTcpSocket 从 qt 运行 运行:

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

其中S为发送数据,R为接收数据

我做了如下代码,我的头文件:

#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

我的 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);
    }
}

当我 运行 我的程序时,我得到:

we are now connected.
Handled HELO 
 "HELO SOME MORE INFORMATION ABOUT THE DEVICE I CONNECTED TO"
Sending:  "DEVC 1.1.1.1 somePassword"

我本以为接下来会收到 DEVC OK,但上面的部分就是我得到的全部。 为什么我没有像终端示例那样收到 DEVC OK

我发现了问题,直到输入了一个新行才写入消息。 在消息中添加 \n 就完成了工作。