7.10作业

闹钟

 

 mainWindow.ccp

 

 TCP服务器

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    server =new QTcpServer(this);

}

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


void MainWindow::on_openBtn_clicked()
{
    //获取输入框中的端口号
    quint16 port=ui->portEdit->text().toUInt();
    //监听获取的端口号
    if(server->listen(QHostAddress::Any,port)){
        QMessageBox::information(this,"成功","打开服务器成功");
    }else
    {
        QMessageBox::information(this,"失败","打开服务器失败");
        return;
    }
      // 连接 newConnection 信号与槽函数 newconnection_slot
    connect(server,&QTcpServer::newConnection,this,&MainWindow::newconnection_slot);
}


//服务器和客户端连接
void MainWindow::newconnection_slot()
{
    //    创建套接字
    QTcpSocket*s=server->nextPendingConnection();
    //将新套接字放入其中
    clientVerctor.push_back(s);
    //每连接一次就执行:readyRead_slot
    connect(s,&QTcpSocket::readyRead,this,&MainWindow::readyRead_slot);
}

//循环读取每个客户端,向客户端发送其他用户发送的信息
void MainWindow::readyRead_slot(){
    // 遍历客户端列表,检查客户端状态
    for(int i=0;i<clientVerctor.size();i++)
    {
        // 如果客户端状态为 0(即已断开连接),则从列表中移除该客户端
        if(clientVerctor[i]->state()==0)
        {
            clientVerctor.removeAt(i);
        }
    }

    // 遍历客户端列表,处理接收到的数据
    for(int i=0;i<clientVerctor.size();i++)
    {
        // 如果客户端有数据可读取
        if(clientVerctor[i]->bytesAvailable()!=0)
        {

            QByteArray msg=clientVerctor[i]->readAll();
            // 在消息列表中添加接收到的消息
            ui->msgWidget->addItem(QString::fromLocal8Bit(msg));Z
            // 将接收到的消息转发给所有客户端
            for(int j=0;j<clientVerctor.size();j++)
            {
                clientVerctor[j]->write(msg);
            }
        }
    }
}

TCP服务器

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值