1/12作业

发布时间:2024年01月15日

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

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
}

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

void Widget::on_btn_connect_clicked()
{
    quint16 port=ui->label_port->text().toUInt();
    if(ser->listen(QHostAddress::Any,port))
    {
        QMessageBox::information(this,"服务器","连接成功");//有客户端连接会发来newconnection
        connect(ser,&QTcpServer::newConnection,this,&Widget::slot_newconnection);
    }
    else
    {
       QMessageBox::information(this,"服务器","连接失败");
    }
}
void Widget::slot_newconnection()
{
    QTcpSocket *new_socket=ser->nextPendingConnection();
    list_socket.push_back(new_socket);
    connect(new_socket,&QTcpSocket::readyRead,this,&Widget::slot_readyread);
}
void Widget::slot_readyread()
{
    for(int i=0;i<list_socket.count();i++)
    {
        if(list_socket.at(i)->state()==0)
        {
            list_socket.removeAt(i);
        }
    }
    for(int j=0;j<list_socket.count();j++)
    {
        if(list_socket.at(j)->bytesAvailable()>0)
        {
           QByteArray msg=list_socket.at(j)->readAll();
           ui->listWidget->addItem(QString::fromUtf8(msg));
           for(int i=0;i<list_socket.count();i++)
           {
               list_socket.at(i)->write(msg);
           }
        }

    }
}

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