QT网络通信TCP客户端实现详解

本文实例为大家分享了QT网络通信TCP客户端实现的具体代码,供大家参考,具体内容如下
QT中基于TCP套接字的网络通信需要用到两个类

  • QTcpServer:服务器类,用于监听客户端连接和客户端建立连接
  • QTcpSocket:通信套接字类,客户端和服务端都需要使用*
这两个类都属于网络通信的network
需要在工程路径下添加network
QT += core gui network
服务器
mainwindow.cpp
#include "mainwindow.h"#include "ui_mainwindow.h"MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent),ui(new Ui::MainWindow){ui->setupUi(this); ui->port->setText("8899"); ui->ip->setText("127.0.0.1"); setWindowTitle("客户端"); m_tcp = new QTcpSocket(this); connect(m_tcp,&QTcpSocket::readyRead,this,[=](){QByteArray data = https://www.it610.com/article/m_tcp->readAll(); ui->record->append("服务端:"+data); }); connect(m_tcp,&QTcpSocket::disconnected,this,[=](){ui->connect->setEnabled(true); ui->disconnect->setDisabled(true); m_tcp->close(); //m_tcp->deleteLater(); //状态释放m_status->setPixmap(QPixmap(":/red.png").scaled(20,20)); ui->record->append("断开连接"); }); connect(m_tcp,&QTcpSocket::connected,this,[=](){m_status->setPixmap(QPixmap(":/green.png").scaled(20,20)); ui->connect->setDisabled(true); ui->disconnect->setEnabled(true); ui->record->append("连接成功"); }); //ui->disconnect->setDisabled(true); m_status = new QLabel; m_status->setPixmap(QPixmap(":/red.png").scaled(20,20)); ui->statusBar->addWidget(new QLabel("连接状态:")); ui->statusBar->addWidget(m_status); }MainWindow::~MainWindow(){delete ui; }void MainWindow::on_sendMsg_clicked(){QString msg = ui->message->toPlainText(); m_tcp->write(msg.toUtf8()); ui->record->append("客户端:"+msg); }void MainWindow::on_connect_clicked(){QString ip=ui->ip->text(); unsigned short port=ui->port->text().toUShort(); m_tcp->connectToHost(QHostAddress(ip),port); ui->connect->setEnabled(false); ui->disconnect->setDisabled(false); }void MainWindow::on_disconnect_clicked(){m_tcp->close(); ui->connect->setEnabled(true); ui->disconnect->setDisabled(true); }

mainwindow.h
#ifndef MAINWINDOW_H#define MAINWINDOW_H#include #include #include #include namespace Ui {class MainWindow; }class MainWindow : public QMainWindow{Q_OBJECTpublic:explicit MainWindow(QWidget *parent = nullptr); ~MainWindow(); private slots:void on_sendMsg_clicked(); void on_connect_clicked(); void on_disconnect_clicked(); private:Ui::MainWindow *ui; QTcpSocket*m_tcp; QLabel*m_status; }; #endif // MAINWINDOW_H

ui文件
MainWindow 00428606MainWindowIP:端口:断开连接连接服务器历史信息发送信息Qt::Horizontal13620发送信息Qt::Horizontal【QT网络通信TCP客户端实现详解】135200042823TopToolBarAreafalse

ui界面
QT网络通信TCP客户端实现详解
文章图片

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

    推荐阅读