您的位置:首页 > 健康 > 美食 > 【QT】

【QT】

2025/4/16 2:47:38 来源:https://blog.csdn.net/m0_70370118/article/details/139840536  浏览:    关键词:【QT】

通信服务端实现

widget.h文件

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QTcpServer>//服务器类
#include <QMessageBox>//消息
#include <QTcpServer>
#include <QList>
#include <QTcpSocket>

QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();

private slots:
    void on_pushButton_2_clicked();

public slots:
    void newConnection_slot();//newConnection槽函数的声明
    void readyRead_slot();

private:
    Ui::Widget *ui;
    QTcpServer *serve;
    QList<QTcpSocket *> socketList;
};
#endif // WIDGET_H

widget.cpp 文件

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
    ,serve(new QTcpServer(this))//服务器指针实例空间
{
    ui->setupUi(this);
}

Widget::~Widget()
{
    delete ui;
}
//服务器对用槽函数
void Widget::on_pushButton_2_clicked()
{
    //获取ui界面上的端口号
    quint16 port = ui->lineEdit->text().toUInt();//将字符串转化成整形
    //监听
    //函数原型 bool listen(const QHostAddress &address = QHostAddress::Any, quint16 port = 0);
    //参数:监听的主机 监听的端口号
    if(serve->listen(QHostAddress::Any,port))//成功返回ture失败返回false
    {
        QMessageBox::information(this,"","启动服务器成功");
    }
    else
    {
        QMessageBox::information(this,"","启动服务器失败");
        return;
    }
    connect(serve,&QTcpServer::newConnection,this,&Widget::newConnection_slot);
}

void Widget::newConnection_slot()
{
    QTcpSocket *s = serve->nextPendingConnection();
    socketList.push_back(s);
    connect(s,&QTcpSocket::readyRead,this,&Widget::readyRead_slot);

}

void Widget::readyRead_slot()
{
    //遍历客户端容器,移除无效客户端
    for(int i=0;i<socketList.count();i++)
        //                   容器元素个数
    {
        //移除无效客户端
        if(socketList.at(i)->state() == 0){
            //删除该元素
            socketList.removeAt(i);
        }
    }
    //遍历客户端容器寻找哪个客户端有数据待读
    for(int i=0;i<socketList.count();i++){
        //函数功能数据的字节大小
        if(socketList.at(i)->bytesAvailable() != 0){//说明有数据
            //读取数据
            QByteArray msg = socketList.at(i)->readAll();
            //将读取到的数据放入ui界面上
            ui->ss->addItem(QString::fromLocal8Bit(msg));
            //将数据广播给所有客户端
            for(int j=0;j<socketList.count();j++){
                socketList.at(j)->write(msg);
            }
        }
    }
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com