TCP断线重连
.h文件
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QTcpSocket> #include <QTimer> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private slots: void on_pushButton_clicked(); void on_pushButton_2_clicked(); void getData(); void reConnectTCP(); void on_pushButton_3_clicked(); private: Ui::MainWindow *ui; QTcpSocket *socket; QTimer *timer; QString ip; quint16 port; }; #endif // MAINWINDOW_H
.cpp文件
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); socket = new QTcpSocket; QObject::connect(socket, SIGNAL(readyRead()), this, SLOT(getData())); timer = new QTimer; // 开启定时器 QObject::connect(timer, SIGNAL(timeout()), this, SLOT(reConnectTCP())); timer->start(10000); } MainWindow::~MainWindow() { delete ui; delete socket; socket = nullptr; } // 连接TCP服务器 void MainWindow::on_pushButton_clicked() { ip = ui->lineEdit->text(); port = ui->lineEdit_2->text().toUInt(); socket->connectToHost(ip, port); } // 断开连接 void MainWindow::on_pushButton_2_clicked() { socket->close(); delete socket; socket = nullptr; qDebug() << "连接已断开"; } // 获取数据 void MainWindow::getData() { QByteArray data = socket->readAll(); ui->textEdit->append(data); } // 重连服务器 void MainWindow::reConnectTCP() { if(!socket){ qDebug() << "已重新连接"; socket = new QTcpSocket; socket->connectToHost(ip, port); QObject::connect(socket, SIGNAL(readyRead()), this, SLOT(getData())); } } // 发送数据 void MainWindow::on_pushButton_3_clicked() { QString str = ui->textEdit_2->toPlainText(); qDebug() << str; socket->write(str.toUtf8()); }
.ui文件