1. Network.h
#include <QtNetwork> class Network : public QWidget { Q_OBJECT public: NetworkPortTransmission(QWidget *parent = nullptr); ~NetworkPortTransmission(); public: void ConnectNet(); void SendMessage(); void ReceiveMessage(); public: QTcpSocket *tcpClient; QByteArray receviedMsg; private: Ui::NetworkPortTransmission *ui; };
2. Network.cpp
Network::Network(QWidget *parent) : QWidget(parent) , ui(new Ui::Network) { ui->setupUi(this); tcpClient = new QTcpSocket; tcpClient->abort(); connect(tcpClient, &QTcpSocket::readyRead, this, &NetworkPortTransmission::ReceiveMessage); }
ConnectNet();
void Network::ConnectNet() { QString ip = ui->lineEdit_ip->text(); QString port = ui->lineEdit_port->text(); if(ui->pushButton_connect->text() == "connect") { if(ip.isEmpty() && port.isEmpty()) { LogMessage("ip or port is NULL"); } else { tcpClient->connectToHost(ip, port.toInt()); } if(!tcpClient->waitForConnected(1000)) { LogMessage("Connection error, please check your network"); return; } ui->lineEdit_ip->setEnabled(false); ui->lineEdit_port->setEnabled(false); ui->pushButton_connect->setText("disconnect"); ui->pushButton_connect->setStyleSheet("color:green"); LogMessage("connect success"); } else { tcpClient->disconnectFromHost(); if(tcpClient->state() == QAbstractSocket::UnconnectedState || tcpClient->waitForDisconnected(1000)) { ui->lineEdit_ip->setEnabled(true); ui->lineEdit_port->setEnabled(true); ui->pushButton_connect->setText("connect"); ui->pushButton_connect->setStyleSheet("color:black"); LogMessage("disconnect success"); } } }
SendMessage();
void NetworkPortTransmission::SendMessage() { QString sendMessage = ui->lineEdit_sendMessage->text(); tcpClient->write(QByteArray::fromHex(sendMessage.toLatin1())); }
ReceiveMessage() ;
void NetworkPortTransmission::ReceiveMessage() { QByteArray msg = tcpClient->readAll(); receviedMsg = msg.toHex().toUpper(); }