QTcpSocket 模拟 netcat '对话'
Posted
技术标签:
【中文标题】QTcpSocket 模拟 netcat \'对话\'【英文标题】:QTcpSocket emulate netcat 'conversation'QTcpSocket 模拟 netcat '对话' 【发布时间】:2020-01-21 14:42:26 【问题描述】:在我的 linux 终端中,我想使用 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
?
【问题讨论】:
【参考方案1】:我发现了问题,直到输入新行才写入消息。
在消息中添加\n
就可以了。
【讨论】:
以上是关于QTcpSocket 模拟 netcat '对话'的主要内容,如果未能解决你的问题,请参考以下文章
同一对象中的 QTcpSocket 到 QTcpSocket
Qt - 当一个类中有多个 QTcpSocket 时,我如何知道哪个 QTcpSocket 发出了 readyRead 信号?