01.13

发布时间:2024年01月13日

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QTcpServer>
#include <QMessageBox>
#include <QList>
#include <QTcpSocket>


namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

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

private slots:

    void on_startBtn_clicked();
public slots:
    void newConnection_slot();
    void readyRead_slot();

private:
    Ui::Widget *ui;
    QTcpServer *server;
    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)
{
    ui->setupUi(this);
    server = new QTcpServer(this);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_startBtn_clicked()
{
    qint16 port=ui->portEdit->text().toUInt();
    if(server->listen(QHostAddress::Any,port))
    {
        QMessageBox::information(this,"提示","服务器启动成功");
    }else
    {
        QMessageBox::information(this,"提示","服务器启动失败");
    }
    connect(server,&QTcpServer::newConnection,this,&Widget::newConnection_slot);
}

void Widget::newConnection_slot()
{
    QTcpSocket *s=server->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->msgWidget->addItem(QString::fromLocal8Bit(msg));
            for(int j=0;j<socketList.count();j++)
            {
                socketList[i]->write(msg);
            }
        }
    }
}

文章来源:https://blog.csdn.net/qq_70290253/article/details/135570139
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。