Qt项目网络聊天室设计

这篇具有很好参考价值的文章主要介绍了Qt项目网络聊天室设计。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

效果演示

Qt项目网络聊天室设计

网络聊天室

Qt网络聊天室服务端

网络聊天室程序

  1. 基于TCP的可靠连接(QTcpServer、QTcpSocket)

  2. 一个服务器,多个客户端

Qt项目网络聊天室设计

  3. 服务器接收到某个客户端的请求以及发送信息,经服务器发给其它客户端 最终实现一个共享聊天内容的聊天室!

QTcpServer

提供一个TCP基础服务类 继承自QObject,这个类用来接收到来的TCP连接,可以指定TCP端口或者用QTcpServer自己挑选一个端口,可以监听一个指定的地址或者所有的机器地址。

QTcpServer的信号:

newConnection()//有新连接连接时触发该信号

配置

pro文件添加

QT += network

获取当前设备所有ip地址

枚举设备所有ip地址

QList<QHostAddress> ipList = QNetworkInterface::allAddresses();
QStringList addressStrList;
addressStrList.clear();

for(int index = 0;index<ipList.size();index++)
{
    if(ipList.at(index).isNull())   continue;         //如果地址为空,则去掉
    QAbstractSocket::NetworkLayerProtocol protocol = ipList.at(index).protocol();
    if(protocol != QAbstractSocket::IPv4Protocol)   continue;           //只取IPV4的地址
    addressStrList.append(ipList.at(index).toString());
}
ui->comboBox_Address->addItems(addressStrList);

listen() close()

调用listen()来监听所有的连接 调用close()来关闭套接字,停止对连接的监听。

如果监听有错误,serverError()返回错误的类型。调用errorString()来把错误打印出来

bool isListening()	const

当服务端正在监听连接时候返回真,否则返回假

QString serverAddressStr = ui->comboBox_Address->currentText();     //获取服务器ip地址
quint16 port = ui->lineEdit_port->text().toInt();                   //获取服务器端口
QHostAddress serverAddress = QHostAddress(serverAddressStr);        //初始化协议族

if(mServer->isListening())
{
    //在监听状态 取消监听
    mServer->close();
}
else
{
    //不在监听状态 开始监听
    if(mServer->listen(serverAddress, port))
    {
        //监听成功
        qDebug() << "Listen Ok!!";
    }
    else
    {
        //监听失败
        QMessageBox::warning(this, "Tcp Server Listen Error", mServer->errorString());
    }
}

当监听连接时候,可以调用serverAddress()serverPort()来返回服务端的地址和端口。

newConnection()

每当一个newConnection新的客户端连接到服务端就会发射信号newConnection()

调用nextPendingConnection()来接受待处理的连接。返回一个连接的QTcpSocket(),我们可以用这个返回的套接字和客户端进行连接

private slots:
    void newConnectionSlot();           //新连接
//处理新连接客户端
connect(mServer, SIGNAL(newConnection()),this, SLOT(newConnectionSlot()));
void Widget::newConnectionSlot()
{
    mClient = mServer->nextPendingConnection();
    connect(mClient, SIGNAL(readyRead()),this, SLOT(readyReadSlot()));//接收消息
    connect(mClient, SIGNAL(disconnected()),this, SLOT(disconnectedSlot()));//断开连接
}

SINGL

readyRead()

客户端有数据发送至服务端时触发该信号

connect(mClient, SIGNAL(readyRead()),this, SLOT(readyReadSlot()));          //接收消息

isReadable

是否可读

readAll

读取客户端发送过来的全部信息

if(mClient->isReadable())
{
	QByteArray recvArray = mClient->readAll();
}

disconnected()

当客户端断开连接时触发该信号

connect(mClient, SIGNAL(disconnected()),this, SLOT(disconnectedSlot()));    //断开连接

UI设计

Qt项目网络聊天室设计

服务端UI设计文章来源地址https://www.toymoban.com/news/detail-497775.html

TcpServer项目训练

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QNetworkInterface>
#include <QAbstractSocket>
#include <QTcpServer>
#include <QTcpSocket>
#include <QMessageBox>
#include <QDateTime>

namespace Ui {
class Widget;
}

class Widget :public QWidget
{
    Q_OBJECT
public:
    explicit Widget(QWidget *parent = nullptr);
    ~Widget();
private slots:
    void on_pushButton_listen_clicked();//开始监听
    void newConnectionSlot();           //新连接
    void disconnectedSlot();            //断开连接
    void readyReadSlot();               //接收消息的槽函数
    void on_pushButton_send_clicked();	//发送消息

private:
    void enumIpAddress();				//枚举当前设备所有端口
private:
    Ui::Widget *ui;

    QTcpServer *mServer;				//服务器
    QTcpSocket *mClient = nullptr;		//客户端
    QList<QTcpSocket *>mClientList;		//客户端链表
};

#endif // WIDGET_H

widget.cpp

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

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    mServer = new QTcpServer;
    enumIpAddress();

    //处理新连接客户端
    connect(mServer, SIGNAL(newConnection()),this, SLOT(newConnectionSlot()));
}

Widget::~Widget()
{
    delete ui;
}
void Widget::enumIpAddress()
{
    QList<QHostAddress> ipList = QNetworkInterface::allAddresses();
    QStringList addressStrList;
    addressStrList.clear();

    for(int index = 0;index<ipList.size();index++)
    {
        if(ipList.at(index).isNull())   continue;         //如果地址为空,则去掉
        QAbstractSocket::NetworkLayerProtocol protocol = ipList.at(index).protocol();
        if(protocol != QAbstractSocket::IPv4Protocol)   continue;           //只取IPV4的地址
        addressStrList.append(ipList.at(index).toString());
    }
    ui->comboBox_Address->addItems(addressStrList);
}

void Widget::on_pushButton_listen_clicked()
{
    QString serverAddressStr = ui->comboBox_Address->currentText();     //获取服务器ip地址
    quint16 port = ui->lineEdit_port->text().toInt();                   //获取服务器端口
    QHostAddress serverAddress = QHostAddress(serverAddressStr);        //初始化协议族

    if(mServer->isListening())
    {
        //在监听状态 取消监听
        mServer->close();
        ui->pushButton_listen->setText("监听");
    }
    else
    {
        //不在监听状态 开始监听
        if(mServer->listen(serverAddress, port))
        {
            //监听成功
            qDebug() << "Listen Ok!!";
            ui->pushButton_listen->setText("停止监听");
        }
        else
        {
            //监听失败
            QMessageBox::warning(this, "Tcp Server Listen Error", mServer->errorString());
        }
    }
}

void Widget::newConnectionSlot()
{
    QString clientInfo;

    mClient = mServer->nextPendingConnection();
    mClientList.append(mClient);
    //窥视Client 信息
    clientInfo = mClient->peerAddress().toString() + ":"+  QString::number(mClient->peerPort());
    ui->listWidget_client->addItem(clientInfo);

    connect(mClient, SIGNAL(readyRead()),this, SLOT(readyReadSlot()));          //接收消息

    connect(mClient, SIGNAL(disconnected()),this, SLOT(disconnectedSlot()));    //断开连接
}

void Widget::readyReadSlot()
{
    QByteArray recvArray;
    QTcpSocket* current = nullptr;
    if(!mClientList.isEmpty())
    {
        //接收客户端数据
        for(int index = 0;index < mClientList.count();index ++)
        {
            current = mClientList.at(index);

            if(current->isReadable())
            {
                recvArray = current->readAll();
                if(recvArray.isEmpty()) continue;
                QString str = QString(QDateTime::currentDateTime().toString("yyyy.MM.dd hh:mm:ss ddd")) +
                        ":Recv\n" + str.fromLocal8Bit(recvArray.data());    //本地GBK转Unicode 解决乱码
                ui->textBrowser_recv->append(str);
                break;
            }
        }
        //转发给其他客户端
        for(int index = 0;index < mClientList.count();index ++)
        {
            QTcpSocket* temp = mClientList.at(index);
            if(current == temp) continue;
            if(temp->isWritable())
            {
                temp->write(recvArray);
            }
        }
    }
}

void Widget::disconnectedSlot()
{
    QMessageBox::information(this, "client close Signal", "client over");
}

void Widget::on_pushButton_send_clicked()
{
    QString sendString = ui->plainTextEdit_send->toPlainText();
    QByteArray sendArr = sendString.toLocal8Bit();

    //群发给所有客户端连接
    if(!mClientList.isEmpty())
    {
        for(int index = 0;index < mClientList.count();index ++)
        {
            QTcpSocket* temp = mClientList.at(index);
            if(temp->isWritable())
            {
                temp->write(sendArr);
            }
        }
    }
    QString str = QString(QDateTime::currentDateTime().toString("yyyy.MM.dd hh:mm:ss ddd"))
            + ":Send\n" + sendString;
    ui->textBrowser_recv->append(str);          //本地GBK转Unicode 解决乱码
}

到了这里,关于Qt项目网络聊天室设计的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【嵌入式学习】网络通信基础-项目篇:简单UDP聊天室

    源码已在GitHub开源:0clock/LearnEmbed-projects/chat 客户端功能: 上线发送登录的用户名[yes] 发送消息和接收消息[yes] quit退出 服务器端功能: 统计用户上线信息,放入链表中[yes] 接收用户信息并给其他用户发送消息[yes] 服务器也支持给所有用户群发消息[yes] 接收下线提醒

    2024年01月25日
    浏览(34)
  • Qt实现简易聊天室

    目录 一、界面展示(界面用ui 设计)  群成员展示界面( denglu)    聊天界面展示( widget ) 二、代码展示 (所有代码非原创)  denglu.h和widget.h  denglu.cpp、main.cpp、widget.cpp 三、软件制作  

    2024年02月08日
    浏览(29)
  • 基于qt软件的网上聊天室软件

    1.服务器:         1).功能: 用于创建一个客户端,通过文本编辑器来获得端口号,根据获得的端口号创建服务器,等待客户端连接 创建成功会提示服务器创建成功 在收到客户端发送的信息时,把这条信息发送给其他所有客户端,实现群聊功能         2).代码: 2.客户端

    2024年02月09日
    浏览(31)
  • Qt实战:云曦聊天室篇——环境部署

    基于Qt的网络聊天室,可进行群聊,私聊,添加好友,创建群聊,添加群聊等功能

    2024年02月05日
    浏览(20)
  • 20230904 QT客户端服务器搭建聊天室

    Ser Cli

    2024年02月09日
    浏览(29)
  • websocket项目 聊天室

    1.项目概述 这个项目是一个基本的实时聊天应用,适用于小型团队或群体。提供了多个聊天室供用户选择。可以通过该代码进行进一步的扩展和定制,例如添加聊天机器人、改进界面等。 2.技术栈 flask,boostrapt,websocket,twemoji 3.项目结构 4.关键特点 Web框架: 项目使用 Flask

    2024年01月20日
    浏览(30)
  • 网络聊天室

    利用UDP协议,实现一套聊天室软件。服务器端记录客户端的地址,客户端发送消息后,服务器群发给各个客户端软件。 问题思考 客户端会不会知道其它客户端地址? UDP 客户端不会直接互连,所以不会获知其它客户端地址,所有客户端地址存储在服务器端。 有几种消息类型

    2024年02月11日
    浏览(21)
  • 网页聊天室项目性能测试报告

    1.1 目的 本测试报告为网页聊天室的性能测试报告,目的在于总结性能测试阶段的学习以及分析测试结果,描述网站是否符合需求。 1.2 背景 考虑到用户数量及数据的增多给服务器造成压力不可估计,因此计划对网页聊天室项目负载性能测试,在系统配置不变的情况下,在一

    2024年02月15日
    浏览(57)
  • 基于UDP实现的网络聊天室

    服务器: 客户端: 运行结果:

    2024年03月08日
    浏览(39)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包