头文件
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include<QTcpServer>            //服务器头文件
#include<QTcpSocket>             //客户端头文件
#include<QList>                  //链表容器
#include<QMessageBox>            //消息对话框
#include<QDebug>
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_startBtn_clicked();
    void newConnection_slot();
    void readyRead_slot();         //自定义处理readyRead信号的槽函数声明
private:
    Ui::Widget *ui;
    //定义服务器指针
    QTcpServer *server;
    //定义客户端容器
    QList<QTcpSocket*>clientList;
};
#endif // WIDGET_H
 
 
main
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //实例化一个服务器
    server=new QTcpServer(this);
    connect(server,&QTcpServer::newConnection,this,&Widget::newConnection_slot);
}
Widget::~Widget()
{
    delete ui;
}
//启动服务器按钮对应的槽函数
void Widget::on_startBtn_clicked()
{
    quint16 port =ui->portEdit->text().toInt();
    if(!server->listen(QHostAddress::Any, port))
    {
        QMessageBox::information(this, "失败", "监听失败");
        return ;
    }else
    {
        QMessageBox::information(this, "成功", "服务器启动成功");
    }
}
//readyRead信号对应的槽函数实现
void Widget:: readyRead_slot()
{
    qDebug()<<"有新的客户端发来请求";
    //获取最新连接的客户端套接字
    QTcpSocket *s=server->nextPendingConnection();
    //将该套接字,放入客户端链表中
    clientList.push_back(s);
    connect(s,&QTcpSocket::readyRead,this,&Widget::readyRead_slot);
}
void Widget:: newConnection_slot()
{
    qDebug()<<"有新的客户端消息发来了";
    //遍历客户端链表,将无效的客户端移除
    for(int i=0; i<clientList.size(); i++)
    {
        //判断当前套接字是否是有效连接
        if(clientList[i]->state() ==0)
        {
            //将该套接字移除客户端容器
            clientList.removeAt(i);
        }
    }
    //遍历客户端链表,判断是哪个客户端发来的数据
    for(int i=0; i<clientList.size(); i++)
    {
        //函数原型:qint64 bytesAvailable() const override;
        //功能:求当前客户端套接字中待读数据的字节数
        //参数:无
        //返回值:待读数据的字节数,如果是0,表示无数据待读
        if(clientList[i]->bytesAvailable() != 0)
        {
            //将该套接字中的数据读取出来
            QByteArray msg = clientList[i]->readAll();
            //将数据展示到ui界面
            ui->msgWidget->addItem( QString::fromLocal8Bit(msg) );
            //将接受到的数据,转发给所有客户端
            for(int j=0; j<clientList.size(); j++)
            {
                clientList[j]->write(msg);
            }
        }
    }
}
 












![[Spring] @Bean 修饰方法时如何注入参数](https://img-blog.csdnimg.cn/141f4aec14694dd8899e9f6a24d67799.png)







