10.4| QT实现TCP服务器客户端搭建的代码,现象

头文件

#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);
            }
        }
    }

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值