7——28homework

代码:

#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()
{
    quint16 port=ui->lineEdit->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()
{
    qDebug()<<"有新的饿了么订单,请及时处理";

    //获取最新连接的客户端套接字
    QTcpSocket* s= server->nextPendingConnection();


    //将该套接字放到客户端容器中
    sockerList.push_back(s);


    connect(s,&QTcpSocket::readyRead,this,&Widget::readyread_slot);
}



void Widget::readyread_slot()
{
    for(int i=0;i<sockerList.count();i++)
    {
        //sockerList.at(i)->state();  //任意一个客户端的状态
        //返回值:套接字状态,是个枚举值,如果为0,表示无效链接
        if(sockerList.at(i)->state()==0)
        {
            //移除该客户端 因为无效链接
            sockerList.removeAt(i);
        }
    }


    //遍历客户端套接字,寻找是哪个客户端有数据可读

    for(int i=0;i<sockerList.count();i++)
    {
        if(sockerList.at(i)->bytesAvailable()!=0)
        {
            QByteArray msg=sockerList.at(i)->readAll();

            //将数据展示到ui界面上
            ui->msgWidget->addItem(QString::fromLocal8Bit(msg));


            //将数据发送给所有客户端
            for(int j=0;j<sockerList.count();j++)
            {
                sockerList.at(j)->write(msg);
            }
        }


    }

}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值