Implementing Simple TCP Communication with QT5

Network sockets using QT s require the addition of a sentence in the. pro file:

  1. QT       += network  

I. Client

1. The client code is slightly simpler than the server. Generally speaking, using the QTcpSocket class in the QT to communicate with the server requires only the following five steps:

(1) Create a QTcpSocket socket object

  1. socket = new QTcpSocket();  

(2) Connect the server with this object

  1. socket->connectToHost(IP, port);  

(3) Send data to server using write function

  1. socket->write(data);  

(4) When new data arrives in socket receiving buffer, readRead() signal will be issued, so slot function is added to read data for the signal.

  1. QObject::connect(socket, &QTcpSocket::readyRead, this, &MainWindow::socket_Read_Data);  
  2.   
  3. void MainWindow::socket_Read_Data()  
  4. {  
  5.     QByteArray buffer;  
  6.     //Read Buffer Data  
  7.     buffer = socket->readAll();  
  8. }  

(5) Disconnect the connection with the server (for the difference between close() and disconnectFromHost(), you can see the help in F1)

  1. socket->disconnectFromHost();  

2. The following are client routines

First, the mainwindow.h file:

  1. //mainwindow.h  
  2. #ifndef MAINWINDOW_H  
  3. #define MAINWINDOW_H  
  4.   
  5. #include <QMainWindow>  
  6. #include <QTcpSocket>  
  7.   
  8. namespace Ui {  
  9. class MainWindow;  
  10. }  
  11.   
  12. class MainWindow : public QMainWindow  
  13. {  
  14.     Q_OBJECT  
  15.   
  16. public:  
  17.     explicit MainWindow(QWidget *parent = 0);  
  18.     ~MainWindow();  
  19.   
  20. private slots:  
  21.   
  22.     void on_pushButton_Connect_clicked();  
  23.   
  24.     void on_pushButton_Send_clicked();  
  25.   
  26.     void socket_Read_Data();  
  27.   
  28.     void socket_Disconnected();  
  29.   
  30. private:  
  31.     Ui::MainWindow *ui;  
  32.     QTcpSocket *socket;  
  33. };  
  34.   
  35. #endif // MAINWINDOW_H  

Then the mainwindow.cpp file:

  1. //mainwindow.cpp  
  2. #include "mainwindow.h"  
  3. #include "ui_mainwindow.h"  
  4.   
  5. MainWindow::MainWindow(QWidget *parent) :  
  6.     QMainWindow(parent),  
  7.     ui(new Ui::MainWindow)  
  8. {  
  9.     ui->setupUi(this);  
  10.   
  11.     socket = new QTcpSocket();  
  12.   
  13.     //Connect signal slot  
  14.     QObject::connect(socket, &QTcpSocket::readyRead, this, &MainWindow::socket_Read_Data);  
  15.     QObject::connect(socket, &QTcpSocket::disconnected, this, &MainWindow::socket_Disconnected);  
  16.   
  17.     ui->pushButton_Send->setEnabled(false);  
  18.     ui->lineEdit_IP->setText("127.0.0.1");  
  19.     ui->lineEdit_Port->setText("8765");  
  20.   
  21. }  
  22.   
  23. MainWindow::~MainWindow()  
  24. {  
  25.     delete this->socket;  
  26.     delete ui;  
  27. }  
  28.   
  29. void MainWindow::on_pushButton_Connect_clicked()  
  30. {  
  31.     if(ui->pushButton_Connect->text() == tr("Connect"))  
  32.     {  
  33.         QString IP;  
  34.         int port;  
  35.   
  36.         //Get IP address  
  37.         IP = ui->lineEdit_IP->text();  
  38.         //Get the port number  
  39.         port = ui->lineEdit_Port->text().toInt();  
  40.   
  41.         //Cancel existing connections  
  42.         socket->abort();  
  43.         //Connecting servers  
  44.         socket->connectToHost(IP, port);  
  45.   
  46.         //Waiting for the connection to succeed  
  47.         if(!socket->waitForConnected(30000))  
  48.         {  
  49.             qDebug() << "Connection failed!";  
  50.             return;  
  51.         }  
  52.         qDebug() << "Connect successfully!";  
  53.   
  54.         //Send key enablement  
  55.         ui->pushButton_Send->setEnabled(true);  
  56.         //Modify keyword text  
  57.         ui->pushButton_Connect->setText("Disconnect");  
  58.     }  
  59.     else  
  60.     {  
  61.         //Disconnect  
  62.         socket->disconnectFromHost();  
  63.         //Modify keyword text  
  64.         ui->pushButton_Connect->setText("Connect");  
  65.         ui->pushButton_Send->setEnabled(false);  
  66.     }  
  67. }  
  68.   
  69. void MainWindow::on_pushButton_Send_clicked()  
  70. {  
  71.     qDebug() << "Send: " << ui->textEdit_Send->toPlainText();  
  72.      //Get the content of the text box and send it as ASCII code  
  73.     socket->write(ui->textEdit_Send->toPlainText().toLatin1());  
  74.     socket->flush();  
  75. }  
  76.   
  77. void MainWindow::socket_Read_Data()  
  78. {  
  79.     QByteArray buffer;  
  80.     //Read Buffer Data  
  81.     buffer = socket->readAll();  
  82.     if(!buffer.isEmpty())  
  83.     {  
  84.         QString str = ui->textEdit_Recv->toPlainText();  
  85.         str+=tr(buffer);  
  86.         //Refresh display  
  87.         ui->textEdit_Recv->setText(str);  
  88.     }  
  89. }  
  90.   
  91. void MainWindow::socket_Disconnected()  
  92. {  
  93.     //Send button failure  
  94.     ui->pushButton_Send->setEnabled(false);  
  95.     //Modify keyword text  
  96.     ui->pushButton_Connect->setText("Connect");  
  97.     qDebug() << "Disconnected!";  
  98. }  

Finally, the design of ui:



Server

1. In addition to using the QTcpSocket class, the server also needs to use the QTcpSever class. Even so, it is only a little more complicated than the client, using six steps:

(1) Create QTcpSever objects

  1. server = new QTcpServer();  


(2) Listen on a port so that the client can access the server using this port

  1. server->listen(QHostAddress::Any, port)  


(3) When the server is accessed by the client, a new Connection () signal is issued, so slot function is added to the signal and a QTcpSocket object is used to receive client access.

  1. connect(server,&QTcpServer::newConnection,this,&MainWindow::server_New_Connect);  
  2.   
  3. void MainWindow::server_New_Connect()  
  4. {  
  5.     //Getting Client Connection  
  6.     socket = server->nextPendingConnection();  
  7. }  

(4) Send data to client using write function of socket

  1. socket->write(data);  

(5) When new data arrives in socket receiving buffer, readRead() signal will be issued, so slot function is added to read data for the signal.

  1. QObject::connect(socket, &QTcpSocket::readyRead, this, &MainWindow::socket_Read_Data);  
  2.   
  3. void MainWindow::socket_Read_Data()  
  4. {  
  5.     QByteArray buffer;  
  6.     //Read Buffer Data  
  7.     buffer = socket->readAll();  
  8. }  

(6) Cancellation of interception

  1. server->close();  

2. The following is the routine of the server

First, the mainwindow.h file:

  1. //mainwindow.h  
  2. #ifndef MAINWINDOW_H  
  3. #define MAINWINDOW_H  
  4.   
  5. #include <QMainWindow>  
  6. #include <QTcpServer>  
  7. #include <QTcpSocket>  
  8.   
  9. namespace Ui {  
  10. class MainWindow;  
  11. }  
  12.   
  13. class MainWindow : public QMainWindow  
  14. {  
  15.     Q_OBJECT  
  16.   
  17. public:  
  18.     explicit MainWindow(QWidget *parent = 0);  
  19.     ~MainWindow();  
  20.   
  21. private slots:  
  22.     void on_pushButton_Listen_clicked();  
  23.   
  24.     void on_pushButton_Send_clicked();  
  25.   
  26.     void server_New_Connect();  
  27.   
  28.     void socket_Read_Data();  
  29.   
  30.     void socket_Disconnected();  
  31.   
  32. private:  
  33.     Ui::MainWindow *ui;  
  34.     QTcpServer* server;  
  35.     QTcpSocket* socket;  
  36. };  
  37.   
  38. #endif // MAINWINDOW_H  

Then the mainwindow.cpp file:

  1. #include "mainwindow.h"  
  2. #include "ui_mainwindow.h"  
  3.   
  4. MainWindow::MainWindow(QWidget *parent) :  
  5.     QMainWindow(parent),  
  6.     ui(new Ui::MainWindow)  
  7. {  
  8.     ui->setupUi(this);  
  9.   
  10.     ui->lineEdit_Port->setText("8765");  
  11.     ui->pushButton_Send->setEnabled(false);  
  12.   
  13.     server = new QTcpServer();  
  14.   
  15.     //Connect signal slot  
  16.     connect(server,&QTcpServer::newConnection,this,&MainWindow::server_New_Connect);  
  17. }  
  18.   
  19. MainWindow::~MainWindow()  
  20. {  
  21.     server->close();  
  22.     server->deleteLater();  
  23.     delete ui;  
  24. }  
  25.   
  26. void MainWindow::on_pushButton_Listen_clicked()  
  27. {  
  28.     if(ui->pushButton_Listen->text() == tr("Interception"))  
  29.     {  
  30.         //Get the port number from the input box  
  31.         int port = ui->lineEdit_Port->text().toInt();  
  32.   
  33.         //Listen on the specified port  
  34.         if(!server->listen(QHostAddress::Any, port))  
  35.         {  
  36.             //If an error occurs, the error message is output  
  37.             qDebug()<<server->errorString();  
  38.             return;  
  39.         }  
  40.         //Modify keyword text  
  41.         ui->pushButton_Listen->setText("Cancel interception");  
  42.         qDebug()<< "Listen succeessfully!";  
  43.     }  
  44.     else  
  45.     {  
  46.         //If you are connecting  
  47.         if(socket->state() == QAbstractSocket::ConnectedState)  
  48.         {  
  49.             //Close connection  
  50.             socket->disconnectFromHost();  
  51.         }  
  52.         //Cancel interception  
  53.         server->close();  
  54.         //Modify keyword text  
  55.         ui->pushButton_Listen->setText("Interception");  
  56.         //Send button failure  
  57.         ui->pushButton_Send->setEnabled(false);  
  58.     }  
  59.   
  60. }  
  61.   
  62. void MainWindow::on_pushButton_Send_clicked()  
  63. {  
  64.     qDebug() << "Send: " << ui->textEdit_Send->toPlainText();  
  65.     //Get the content of the text box and send it as ASCII code  
  66.     socket->write(ui->textEdit_Send->toPlainText().toLatin1());  
  67.     socket->flush();  
  68. }  
  69.   
  70. void MainWindow::server_New_Connect()  
  71. {  
  72.     //Getting Client Connection  
  73.     socket = server->nextPendingConnection();  
  74.     //Connect the signal slot of the QTcpSocket to read the new data  
  75.     QObject::connect(socket, &QTcpSocket::readyRead, this, &MainWindow::socket_Read_Data);  
  76.     QObject::connect(socket, &QTcpSocket::disconnected, this, &MainWindow::socket_Disconnected);  
  77.     //Send key enablement  
  78.     ui->pushButton_Send->setEnabled(true);  
  79.   
  80.     qDebug() << "A Client connect!";  
  81. }  
  82.   
  83. void MainWindow::socket_Read_Data()  
  84. {  
  85.     QByteArray buffer;  
  86.     //Read Buffer Data  
  87.     buffer = socket->readAll();  
  88.     if(!buffer.isEmpty())  
  89.     {  
  90.         QString str = ui->textEdit_Recv->toPlainText();  
  91.         str+=tr(buffer);  
  92.         //Refresh display  
  93.         ui->textEdit_Recv->setText(str);  
  94.     }  
  95. }  
  96.   
  97. void MainWindow::socket_Disconnected()  
  98. {  
  99.     //Send button failure  
  100.     ui->pushButton_Send->setEnabled(false);  
  101.     qDebug() << "Disconnected!";  
  102. }  

Finally, the design of ui:



3. Operation results



Keywords: socket Qt network ascii

Added by scuzzo84 on Tue, 21 May 2019 02:34:14 +0300