Qt creator day5练习

Qt 中实现TCP 聊天服务器

大致流程

创建套接字服务器QTcpServer对象

通过QTcpServer对象设置监听,即QTcpServer::listen()

基于QTcpServer::newConnection()信号检测是否有新的客户端连接

如果有新的客户端连接 调用QTcpSocket *QTcpServer::nextPendingConnection()得到通信的套接字对象

使用通信的套接字对象QTcpSocket和客户端进行通信

.pro文件

QT       += core gui network    # 所需模块network 添加后记得构建

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++11

# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
    main.cpp \
    widget.cpp

HEADERS += \
    widget.h

FORMS += \
    widget.ui

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

.h文件

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QTcpServer>  //??包含TCP服务器类
#include <QMessageBox> //消息对话框类
#include <QTcpSocket>  //包含客户端类

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; //创建一个套接字服务器QTcpServer对象 在构造函数初始化列表中初始化

    QList<QTcpSocket *> socketList;  //定义一个存放客户套接字的容器
};
#endif // WIDGET_H

main.cpp

#include "widget.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();
    return a.exec();
}

.cpp文件

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

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
    ,server(new QTcpServer(this))  //初始化列表 初始化server
{
    ui->setupUi(this);

}

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


void Widget::on_startBtn_clicked()
{
    //定义一个 quint16 类型的变量port 接收 字符串端口转换成 整型的端口
    quint16 port = ui->portEdit->text().toUInt();

    //调用 QTcpServer类型的对象server里的listen函数,实现监听
    if(server->listen(QHostAddress::Any,port))
    {
        //启动监听成功
        QMessageBox::information(this,"","启动服务器成功");
    }
    else
    {
        //启动监听失败
        QMessageBox::critical(this,"","启动服务器失败");
    }

    //此时服务器已经成功启动监听,如果有客户端发来连接,那么服务器端就会自动发射一个newConnection()的信号
    //将该信号连接到自定义的槽函数中
    connect(server,&QTcpServer::newConnection,this,&Widget::newConnection_slot);

}

//newConnection_slot()槽函数的实现
//有客户端连接时,服务器发射一个newConnection信号后,执行这个函数
void Widget::newConnection_slot()
{
    //使用QTcpSocket *QTcpServer::nextPenddingConnection()函数得到通信的套接字对象
    QTcpSocket *s = server->nextPendingConnection();
    socketList.push_back(s);  // 用尾插法将套接字放入链表
    //如果有客户端发来数据,客户端就会自动发射一个readyRead信号,就可以将该信号连接到自定义的槽函数中
    connect(s,&QTcpSocket::readyRead,this,&Widget::readyRead_slot);

}

//客户端发射信号对应的槽函数的实现
void Widget::readyRead_slot()
{
    //遍历有效客户端,移除无效客户端
    for(int i=0; i<socketList.count(); i++)
    {
        if(socketList.at(i)->state() == 0)
        {
            socketList.removeAt(i); //删除该元素
        }
    }

    //再遍历客户端容器,寻找哪个客户端的数据待读
    for(int i=0; i<socketList.count(); i++)
    {
        if(socketList.at(i)->bytesAvailable() != 0)
        {
            //!= 0 说明这些是有效数据
            QByteArray msg = socketList.at(i)->readAll();
            //将读取到的数据 放到ui界面上
            ui->listWidget->addItem(QString::fromLocal8Bit(msg));  //fromlocal8bit() 将Windows的GBK字符转换为Qt的Unicode
                                                                   //QString::Local8bit是本地操作系统设置的字符集编码
            //将数据广播给所有客户端
            for(int i=0; i<socketList.count(); i++)
            {
                socketList.at(i)->write(msg);
            }
        }
    }

}


























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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值