Qt下QTcpServer服务端识别多个QTcpSocket客户端

news/2024/10/17 6:27:45/

文章目录

  • Qt官方文档
  • 编写QTcpServerDemo和QTcpSocketDemo
    • 实现QTcpServerDemo
    • 实现QTcpSocketDemo
  • 使用windeployqt生成程序运行所需依赖文件

Qt官方文档

QTcpSocket Class :https://doc.qt.io/qt-5/qtcpsocket.html
QAbstractSocket Class:https://doc.qt.io/qt-5/qabstractsocket.html
QTcpServer Class:https://doc.qt.io/qt-5/qtcpserver.html

编写QTcpServerDemo和QTcpSocketDemo

看一下效果先:

在这里插入图片描述

实现QTcpServerDemo

头文件:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>
#include <QTcpServer>
#include <QTcpSocket>
#include <QNetworkConfigurationManager>
#include <QNetworkInterface>QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACEclass MainWindow : public QMainWindow
{Q_OBJECTpublic:MainWindow(QWidget *parent = nullptr);~MainWindow();
public slots:/// 服务端接收到客户端连接的槽函数void TcpServerConnected();/// 服务端接收客户端发送的数据的槽函数void ReadAllData();/// 客户端连接断开的槽函数void ClientDisconnected();private slots:/// 点击启动按钮void on_btnRun_clicked();private:Ui::MainWindow *ui;/// QTcpServer是服务端QTcpServer *tcpServer = nullptr;/// QTcpSocket是服务端程序用来与客户端进行通信的QTcpSocket *tcpSocket = nullptr;/// 用来存储来自客户端的连接QList<QTcpSocket*> tcpSocketList;};
#endif // MAINWINDOW_H

源文件:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);tcpServer = new QTcpServer(this); // 构造函数中实例化tcpServerconnect(tcpServer,&QTcpServer::newConnection,this,&MainWindow::TcpServerConnected); // 当有客户端连接到服务端就执行TcpServerConnected槽函数
}MainWindow::~MainWindow()
{delete ui;for(auto client : tcpSocketList)client->close();
}/// 点击启动按钮
void MainWindow::on_btnRun_clicked()
{QHostAddress address = QHostAddress("127.0.0.1"); // ipint port = 5023; // 端口if(tcpServer->isListening()) // 判断服务端是否开启了监听{tcpServer->close()for(auto client : tcpSocketList)client->close();tcpSocketList.clear();ui->label->setText(QString("关闭监听成功,%1:%2").arg(address.toString()).arg(port));ui->btnRun->setText("开启");}else{if(!tcpServer->listen(address,port)) // 服务端开启监听ui->label->setText(QString("开启监听失败,%1:%2").arg(address.toString()).arg(port));else{ui->label->setText(QString("开启监听成功,%1:%2").arg(address.toString()).arg(port));ui->btnRun->setText("关闭");}}}/// 当有客户端连接到服务端
void MainWindow::TcpServerConnected()
{tcpSocket = tcpServer->nextPendingConnection();if(!tcpSocketList.contains(tcpSocket))tcpSocketList.append(tcpSocket);connect(tcpSocket,&QTcpSocket::readyRead,this,&MainWindow::ReadAllData);connect(tcpSocket,&QTcpSocket::disconnected,this,&MainWindow::ClientDisconnected);ui->txtLog->append(tcpSocket->localAddress().toString() + " 已连接");
}/// 服务端接收客户端发送的数据
void MainWindow::ReadAllData()
{QTcpSocket *client = dynamic_cast<QTcpSocket*>(sender());QByteArray buff = client->readAll();qDebug() << buff;ui->txtLog->append(buff);client->write(buff);
}/// 当关闭与客户端的连接时
void MainWindow::ClientDisconnected()
{QTcpSocket *client = dynamic_cast<QTcpSocket*>(sender());QString msg = QString("触发断开连接,%1:%2").arg(client->peerAddress().toString()).arg(client->peerPort());qDebug() << msg;ui->txtLog->append(msg);
}

实现QTcpSocketDemo

头文件:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>
#include <QTcpSocket>
#include <QTcpServer>
#include <QNetworkInterface>QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACEclass MainWindow : public QMainWindow
{Q_OBJECTpublic:MainWindow(QWidget *parent = nullptr);~MainWindow();public slots:void ReadAllData();void Connected();void Disconnected();private slots:void on_btnSend_clicked();void on_btnDisconnect_clicked();private:Ui::MainWindow *ui;QTcpSocket *tcpSocket = nullptr;QHostAddress address;int port;
};
#endif // MAINWINDOW_H

源文件:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);tcpSocket = new QTcpSocket(this);connect(tcpSocket,&QTcpSocket::readyRead,this,&MainWindow::ReadAllData);connect(tcpSocket,&QTcpSocket::connected,this,&MainWindow::Connected);connect(tcpSocket,&QTcpSocket::disconnected,this,&MainWindow::Disconnected);address = QHostAddress("127.0.0.1");port = 5023;ui->txtIp->setText(address.toString());ui->txtPort->setText(QString::number(port));
}MainWindow::~MainWindow()
{delete ui;
}void MainWindow::ReadAllData()
{QByteArray buff = tcpSocket->readAll();qDebug() << buff;ui->txtLog->append(buff);
}void MainWindow::Connected()
{QString address = tcpSocket->peerAddress().toString();int port = tcpSocket->peerPort();qDebug() << QString("连接成功, %1:%2").arg(address).arg(port);ui->txtLog->append(QString("连接成功, %1:%2").arg(address).arg(port));
}void MainWindow::Disconnected()
{ui->txtIp->setEnabled(true);ui->txtPort->setEnabled(true);ui->btnSend->setText("连接");
}void MainWindow::on_btnSend_clicked()
{QString txt = ui->txtSend->toPlainText();tcpSocket->write(txt.toStdString().c_str());
}void MainWindow::on_btnDisconnect_clicked()
{address = QHostAddress(ui->txtIp->text());port = ui->txtPort->text().toInt();if(tcpSocket->state() == QTcpSocket::SocketState::ConnectedState){ui->txtIp->setEnabled(true);ui->txtPort->setEnabled(true);tcpSocket->disconnectFromHost();ui->btnDisconnect->setText("连接");}else{ui->txtIp->setEnabled(false);ui->txtPort->setEnabled(false);tcpSocket->connectToHost(address.toString(),port);ui->btnDisconnect->setText("断开");}
}

使用windeployqt生成程序运行所需依赖文件

确认编译环境:

在这里插入图片描述
在对应编译环境目录下运行 windeployqt 生成运行程序所需的依赖文件:

在这里插入图片描述


http://www.ppmy.cn/news/126500.html

相关文章

FR107对应 RS1M

FR307对应 RS3M FR107对应 RS1M 1N4007对应 M7 5KP48 功率5KW&#xff0c;截止电压VBR48V 5KP33 功率5KW,截止电压VBR33V

计算机维护与维修毕业论文,计算机维修与维护毕业论文.doc

PAGE PAGE 2 . 计算机维护与维修 实验报告 所属课程名称﹕ 计算机维护与维修 任 课 教 师 ﹕ 班 级 ﹕ 学 号 ﹕ 姓 名 ﹕ 实 验 日 期 ﹕ 摘要 在现代的社会中&#xff0c;计算机的使用越来越频繁。很多人开始自己组装电脑、安装系统.但是在其使用和操作的过程中&#xff0c;可…

L1-060~L1-062

题目 这是一幅心理阴影面积图。我们都以为自己可以匀速前进&#xff08;图中蓝色直线&#xff09;&#xff0c;而拖延症晚期的我们往往执行的是最后时刻的疯狂赶工&#xff08;图中的红色折线&#xff09;。由红、蓝线围出的面积&#xff0c;就是我们在做作业时的心理阴影面积…

L201

The American public’s obsession with dieting has led to one of the most dangerous healthmisconceptions of all times. Many television ads, movies, magazine articles, and diet-food product labelswould have consumers believe that carbohydrates(碳水化合物)are…

L1-039~L1-041

题目 中国的古人写文字&#xff0c;是从右向左竖向排版的。本题就请你编写程序&#xff0c;把一段文字按古风排版。 输入格式&#xff1a; 输入在第一行给出一个正整数N&#xff08;<100&#xff09;&#xff0c;是每一列的字符数。第二行给出一个长度不超过1000的非空字符…

COPRA RF 2005 SR1

COPRA RF 2005 SR1最新版 冷弯成型&#xff0c;轧辊设计 USB加密锁 本软件破解完整&#xff0c;带有USB加密锁&#xff0c;没有功能使用限制&#xff0c; ************************************************************************Buy E-mail: ywcwsoftsohu.com 或 ywcwso…

Layotto v0.4.0-rc 发布

Layotto v0.4.0-rc 发布 v0.4.0-rc 版本包含以下功能提升和问题修复&#xff1a; 1.文件能力增加了七牛云 oss、hdfs、腾讯云 oss 的实现&#xff1b;同时增加了 Java SDK 的实现 2.支持 API 插件和自定义组件能力 3.支持 skywalking 4.支持基于内存的和 mongo 的分布式锁…

p1001

1.求int型数据在内存中存储时1的个数 输入一个int型数据&#xff0c;计算出该int型数据在内存中存储时1的个数。 我们很容易想到如下方法&#xff1a; [cpp] view plain copy print ? #include <iostream> using namespace std; int main() { int n,cnt0; …