夜雨聆风学习资料网

ARTICLE · 1373509

程序员进阶必看:5万行源码打造《企业即时通讯系统》

程序员进阶必看:5万行源码打造《企业即时通讯系统》

欢迎来到【Qt开发笔记】微信公众号【知识宝库】!

本系列【Qt C++开发工程师】项目实战 第228期,本期我们聚焦一个兼具实用性与学习深度的主题——👉《程序员进阶必看:5万行源码打造《企业即时通讯系统》》。本系列文章旨在为关注Qt跨平台开发、C++后端开发及系统底层架构的开发者,提供一个系统的学习参考。内容将通过原理讲解与实战结合的方式,解析相关核心知识与设计思路,以期对您的技术探索与实践有所裨益。
这个工程项目实例,适合三类人:
  • 第一类,想提升项目实战能力的 Qt/C++ 开发者。
  • 第二类,正在准备简历项目的应届生。

  • 第三类,想做项目架构二次开发和创新功能的人。

⭐关注博主后私信领取源码/学习资料📑VX:vico2588。

一、【工程项目运行】

1、服务器--启动失败

2、服务器--启动成功

仪表盘:

用户管理:

文件审计:

3、客户端1--登录

4、客户端2--登录

5、服务器--监控信息

二、【工程项目简介】

1、项目简介

EIM(Enterprise Instant Messaging)是一套C/S架构的企业内部即时通信软件:

  • EIMServer:管理员控制台+TCP业务服务。启动后先配数据库,再管理员登录,在界面里启动监听。负责认证、好友/群、消息路由、离线存储、文件中转、审计、备份、监控。

  • EIMClient:员工桌面客户端。登录/注册后进行单聊、群聊、好友与群管理、文件/图片收发。支持断线重连、已读回执、离线消息、群公告/禁言、组织架构、强制下线与远程擦除。

典型使用场景:

  • 企业内部办公即时沟通(文本 + 图片 + 文件)

  • 管理员对账号、消息、文件、群组做审计与运维

  • 合规场景下的强制下线、远程擦除、操作日志留存

2、系统架构设计

2.1 总体结构

2.2 服务端分层

  • 表现层:MainWindow、Dashboard、UserManager、MessageAudit、AuditLogView、GroupManager、FileAudit、SystemConfig、BackupManager、RoleManager。管理员UI,信号槽驱动。

  • 接入层:NetworkServer、ClientSession。QTcpServer在独立网络线程接入;按包头拆包;心跳超时踢线;会话引用计数延后销毁。

  • 业务层:BusinessHandler/businesshandler2.cpp。按MsgId分发:认证、好友、消息、群、文件、组织搜索。

  • 数据层:DatabaseManager(拆分1–6个cpp)、ConnectionPool、DbGuard。业务SQL;每线程独立ODBC连接。

  • 运维层:SystemMonitor、BackupManager。PDH 采CPU/内存/磁盘;mysqldump/mysql备份恢复。

服务端启动顺序(EIMServer/src/main.cpp):

  • 创建C:/IMServer/{files,backups,logs}

  • DbConfigDialog:选ODBC驱动并连库,成功后DatabaseManager::initDatabase()建表、补默认管理员、纠正群主角色/部门树。

  • LoginManager:管理员登录。

  • MainWindow:左侧导航+内容页;需手动点「启动服务」才开始监听8080。

NetworkServer无父对象,构造后立刻startNetworkThread(),QTcpServer跑在网络线程。业务包(除心跳、文件分片保序)经BusinessHandler::runAsync进入QThreadPool。

2.3 客户端分层

  • UI:LoginWindow、`MainWindow、ChatWidget、UiScale。登录注册、好友/群菜单、会话、禁言/公告对话框、高分屏缩放。

  • 会话:SessionManager。登录态、心跳、重连、协议收发、文件分片状态机。

  • 传输:TcpClient。QTcpSocket粘包拆包。

  • 本地:LocalCache、SecureStore。SQLite消息缓存(打开会话先读缓存);DPAPI记住密码。

客户端启动顺序(EIMClient/src/main.cpp):

  • 高DPI属性 + UiScale::init(设计稿1920×1080,主窗1200×760)

  • LoginWindow(可注册新用户)

  • 登录成功→MainWindow

  • 拉好友列表、群列表;定时拉组织架构

2.4 线程模型

  • UI线程:管理端界面、监控定时器、状态栏;通过Queued信号收在线人数。

  • 网络线程:QTcpServer、ClientSession读写、心跳定时器、文件分片收发。

  • QThreadPool:登录/消息/群/组织树等业务SQL;下线后写offline并推好友。

  • 每工作线程:ConnectionPool按eim_thr_<tid>建独立ODBC连接,避免跨线程共用QSqlDatabase。

锁约定:NetworkServer::m_rwLock为Recursive;持锁时只做哈希表快照,推送在锁外pushToUser。

3、工程目录结构

三、【工程核心源码】

1、chatwidget.h
#pragma once#include<QWidget>#include<QTextBrowser>#include<QPlainTextEdit>#include<QPushButton>#include<QStringList>#include<QUrl>#include<QElapsedTimer>class SessionManager;class ChatWidget : public QWidget{    Q_OBJECTpublic:    explicitChatWidget(SessionManager *session, QWidget *parent = nullptr);signals:    voidsendText(QString text);    voidsendFile(QString filePath);    voidlinkClicked(QString url);  // 用户点击了聊天中的链接    voidreachedTop();    voidrecallRequested();    voidblocksTrimmed(int droppedFront);protected:    booleventFilter(QObject *obj, QEvent *event)override;private slots:    voidonSend();    voidonSendFile();public slots:    voidappendMessage(const QString &line);    intappendMessageTracked(const QString &line);    intprependMessageTracked(const QString &line);    voidupdateMessageAt(int index, const QString &line);    voidappendSuffixAt(int index, const QString &suffix, const QString &dedupToken = QString());    voidclearMessages();private:    voidrenderMessages(bool stickToBottom);    voidpinScroll(bool stickToBottom, int generation, int oldValue, int oldMax);    voidappendHtmlTail(const QString &line);    inttrimFrontIfNeeded();private:    SessionManager *m_session{nullptr};    QTextBrowser *m_view{nullptr};    QPlainTextEdit *m_input{nullptr};    QPushButton *m_sendBtn{nullptr};    QPushButton *m_fileBtn{nullptr};    QStringList m_blocks;    QElapsedTimer m_topEmitAt;    bool m_suppressTop{false};    int m_scrollGen{0};    static const int kMaxBlocks = 400;};
2、chatwidget.cpp
#include"chatwidget.h"#include"uiscale.h"#include<QVBoxLayout>#include<QHBoxLayout>#include<QScrollBar>#include<QFileDialog>#include<QMimeDatabase>#include<QKeyEvent>#include<QIcon>#include<QMenu>#include<QAction>#include<QTextCursor>#include<QTextDocument>#include<QTextOption>#include<QTimer>ChatWidget::ChatWidget(SessionManager *session, QWidget *parent)    : QWidget(parent), m_session(session){    auto *root = new QVBoxLayout(this);    root->setContentsMargins(UiScale::px(8), UiScale::px(8), UiScale::px(8), UiScale::px(8));    root->setSpacing(UiScale::px(8));    m_view = new QTextBrowser(this);    m_view->setOpenLinks(false); // 不自动打开,由我们处理    m_view->setOpenExternalLinks(false);    m_view->setLineWrapMode(QTextEdit::WidgetWidth);    m_view->setWordWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);    m_view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);    connect(m_view, &QTextBrowser::anchorClicked, this, [this](const QUrl &url){        emit linkClicked(url.toString());    });    root->addWidget(m_view, 3);    auto *inputPanel = new QWidget(this);    auto *inputLay = new QVBoxLayout(inputPanel);    inputLay->setContentsMargins(0, 0, 0, 0);    inputLay->setSpacing(UiScale::px(6));    m_input = new QPlainTextEdit(this);    m_input->setLineWrapMode(QPlainTextEdit::WidgetWidth);    m_input->setPlaceholderText(QStringLiteral("输入消息,Enter 发送,Shift+Enter 换行"));    m_input->setMinimumHeight(UiScale::fontPx(88));    m_input->setStyleSheet(QStringLiteral(        "QPlainTextEdit {"        "  border: 1px solid #d5deee;"        "  border-radius: 4px;"        "  padding: 6px;"        "  background: #ffffff;"        "  color: #24324a;"        "  font-size: %1px;"        "  selection-background-color: #d7e6ff;"        "  selection-color: #1d3f74;"        "}"    ).arg(UiScale::fontPx(13)));    m_input->installEventFilter(this);    inputLay->addWidget(m_input, 1);    auto *btnRow = new QHBoxLayout;    btnRow->setSpacing(UiScale::px(8));    btnRow->addStretch(1);    m_fileBtn = new QPushButton("文件", this);    m_sendBtn = new QPushButton("发送", this);    const QSize btnSize(UiScale::fontPx(110), UiScale::fontPx(34));    const QSize iconSize(UiScale::fontPx(18), UiScale::fontPx(18));    m_sendBtn->setIcon(QIcon(QStringLiteral(":/new/prefix1/images/sendmsg.ico")));    m_fileBtn->setIcon(QIcon(QStringLiteral(":/new/prefix1/images/sendfile.ico")));    m_sendBtn->setIconSize(iconSize);    m_fileBtn->setIconSize(iconSize);    m_fileBtn->setFixedSize(btnSize);    m_sendBtn->setFixedSize(btnSize);    btnRow->addWidget(m_sendBtn);    btnRow->addWidget(m_fileBtn);    inputLay->addLayout(btnRow);    inputPanel->setMinimumHeight(UiScale::fontPx(130));    root->addWidget(inputPanel, 1);    connect(m_sendBtn, &QPushButton::clicked, this, &ChatWidget::onSend);    connect(m_fileBtn, &QPushButton::clicked, this, &ChatWidget::onSendFile);    m_view->setContextMenuPolicy(Qt::CustomContextMenu);    connect(m_view, &QWidget::customContextMenuRequested, this, [this](const QPoint &pos){        QMenu menu(this);        QAction *recall = menu.addAction(QStringLiteral("撤回"));        const QAction *chosen = menu.exec(m_view->mapToGlobal(pos));        if (chosen == recall)            emit recallRequested();    });    connect(m_view->verticalScrollBar(), &QScrollBar::valueChanged, this, [this](int v){        if (m_suppressTop || v != 0) return;        auto *bar = m_view->verticalScrollBar();        if (!bar || bar->maximum() <= 0) return;        if (m_topEmitAt.isValid() && m_topEmitAt.elapsed() < 400)            return;        m_topEmitAt.start();        emit reachedTop();    });}boolChatWidget::eventFilter(QObject *obj, QEvent *event){    if (obj == m_input && event->type() == QEvent::KeyPress) {        auto *ke = static_cast<QKeyEvent *>(event);        if (ke->key() == Qt::Key_Return || ke->key() == Qt::Key_Enter) {            if (ke->modifiers() & Qt::ShiftModifier) {                return false; // Shift+Enter 换行            }            onSend();            return true;        }    }    return QWidget::eventFilter(obj, event);}voidChatWidget::onSend(){    const QString text = m_input->toPlainText().trimmed();    if (text.isEmpty()) return;    emit sendText(text);    m_input->clear();}voidChatWidget::onSendFile(){    QString path = QFileDialog::getOpenFileName(this, "选择文件", QString(),        "所有文件 (*.*);;\u56fe片 (*.png *.jpg *.jpeg *.gif *.bmp);;文档 (*.pdf *.docx *.xlsx *.txt)");    if (path.isEmpty()) return;    emit sendFile(path);}voidChatWidget::appendMessage(const QString &line){    appendMessageTracked(line);}intChatWidget::appendMessageTracked(const QString &line){    m_blocks.append(line);    const int dropped = trimFrontIfNeeded();    if (dropped > 0)        emit blocksTrimmed(dropped);    renderMessages(true);    return m_blocks.size() - 1;}intChatWidget::prependMessageTracked(const QString &line){    m_blocks.prepend(line);    renderMessages(false);    return 0;}voidChatWidget::updateMessageAt(int index, const QString &line){    if (index < 0 || index >= m_blocks.size()) return;    m_blocks[index] = line;    renderMessages(true);}voidChatWidget::appendSuffixAt(int index, const QString &suffix, const QString &dedupToken){    if (index < 0 || index >= m_blocks.size()) return;    if (!dedupToken.isEmpty() && m_blocks[index].contains(dedupToken)) return;    const QString close = QStringLiteral("</p>");    const int pos = m_blocks[index].lastIndexOf(close);    if (pos >= 0)        m_blocks[index].insert(pos, suffix);    else        m_blocks[index] += suffix;    renderMessages(true);}voidChatWidget::clearMessages(){    m_blocks.clear();    m_view->clear();}intChatWidget::trimFrontIfNeeded(){    int dropped = 0;    while (m_blocks.size() > kMaxBlocks) {        m_blocks.removeFirst();        ++dropped;    }    return dropped;}voidChatWidget::appendHtmlTail(const QString &line){    auto *bar = m_view->verticalScrollBar();    const bool stickBottom = !bar || bar->value() >= bar->maximum() - 8;    QTextCursor c(m_view->document());    c.movePosition(QTextCursor::End);    if (m_blocks.size() > 1)        c.insertHtml(QStringLiteral("<div style='height:2px;'></div>") + line);    else        c.insertHtml(line);    if (stickBottom && bar)        bar->setValue(bar->maximum());}voidChatWidget::pinScroll(bool stickToBottom, int generation, int oldValue, int oldMax){    if (generation != m_scrollGen) return;    auto *bar = m_view->verticalScrollBar();    if (!bar) return;    m_suppressTop = true;    if (m_view->document())        m_view->document()->setTextWidth(qMax(1, m_view->viewport()->width()));    if (stickToBottom) {        QTextCursor cursor(m_view->document());        cursor.movePosition(QTextCursor::End);        m_view->setTextCursor(cursor);        m_view->ensureCursorVisible();        bar->setValue(bar->maximum());    } else {        const int grown = qMax(0, bar->maximum() - oldMax);        bar->setValue(qBound(0, oldValue + grown, bar->maximum()));    }}voidChatWidget::renderMessages(bool stickToBottom){    ++m_scrollGen;    const int generation = m_scrollGen;    m_suppressTop = true;    auto *bar = m_view->verticalScrollBar();    const int oldValue = bar ? bar->value() : 0;    const int oldMax = bar ? bar->maximum() : 0;    m_view->setHtml(m_blocks.join("<div style='height:2px;'></div>"));    m_view->setLineWrapMode(QTextEdit::WidgetWidth);    m_view->setWordWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);    pinScroll(stickToBottom, generation, oldValue, oldMax);    QTimer::singleShot(0, this, [this, stickToBottom, generation, oldValue, oldMax]() {        pinScroll(stickToBottom, generation, oldValue, oldMax);        if (generation == m_scrollGen)            m_suppressTop = false;    });}
3、localcache.h
#pragma once#include<QObject>#include<QSqlDatabase>#include<QJsonObject>#include<QJsonArray>class LocalCache : public QObject{    Q_OBJECTpublic:    explicitLocalCache(QObject *parent = nullptr);    ~LocalCache();    boolopen(const QString &username);    voidsaveMessage(const QJsonObject &msg);    voidsaveMessage(const QJsonObject &msg, const QString &chatType, int peerId);    QJsonArray loadMessages(const QString &chatType, int peerId, int limit = 50);    voidclearAll();private:    voidpruneChat(const QString &chatType, int peerId, int keep);private:    QSqlDatabase m_db;    QString m_connName;    QString m_dbPath;};
4、localcache.cpp
#include"localcache.h"#include<QSqlQuery>#include<QSqlError>#include<QDir>#include<QFile>#include<QStandardPaths>#include<QJsonDocument>#include<QList>#include<QVariant>LocalCache::LocalCache(QObject *parent) : QObject(parent) {}LocalCache::~LocalCache(){    if (m_db.isOpen()) {        m_db.close();    }    m_db = QSqlDatabase();    if (!m_connName.isEmpty()) {        QSqlDatabase::removeDatabase(m_connName);        m_connName.clear();    }}boolLocalCache::open(const QString &username){    if (m_db.isOpen()) return true;    QString base = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);    QDir().mkpath(base);    m_dbPath = base + "/" + username + "_cache.db";    m_connName = "cache_" + username;    m_db = QSqlDatabase::addDatabase("QSQLITE", m_connName);    m_db.setDatabaseName(m_dbPath);    if (!m_db.open()) return false;    QSqlQuery q(m_db);    q.exec("CREATE TABLE IF NOT EXISTS chat_cache ("           "id INTEGER PRIMARY KEY AUTOINCREMENT,"           "msg_json TEXT NOT NULL,"           "create_time DATETIME DEFAULT CURRENT_TIMESTAMP)");    q.exec("ALTER TABLE chat_cache ADD COLUMN chat_type TEXT");    q.exec("ALTER TABLE chat_cache ADD COLUMN peer_id INTEGER");    q.exec("ALTER TABLE chat_cache ADD COLUMN msg_id INTEGER");    q.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_cache_msgid ON chat_cache(msg_id)");    return true;}voidLocalCache::saveMessage(const QJsonObject &msg){    QString chatType = msg.value("chat_type").toString("single");    int peerId = msg.value("peer_id").toInt();    if (peerId <= 0) {        if (chatType == QLatin1String("group")) {            peerId = msg.value("group_id").toInt();            if (peerId <= 0) peerId = msg.value("to_id").toInt();        } else {            peerId = msg.contains("to_user") ? msg.value("to_user").toInt() : msg.value("to_id").toInt();        }    }    saveMessage(msg, chatType, peerId);}voidLocalCache::saveMessage(const QJsonObject &msg, const QString &chatType, int peerId){    if (!m_db.isOpen()) return;    const qint64 msgId = msg.value("msg_id").toVariant().toLongLong();    if (msgId <= 0 || peerId <= 0) return;    QJsonObject stored = msg;    stored["chat_type"] = chatType;    stored["peer_id"] = peerId;    if (chatType == QLatin1String("group") && stored.value("group_id").toInt() <= 0)        stored["group_id"] = peerId;    QSqlQuery q(m_db);    q.prepare("INSERT OR REPLACE INTO chat_cache(msg_json, chat_type, peer_id, msg_id) VALUES(:m,:t,:p,:id)");    q.bindValue(QStringLiteral(":m"),                QVariant(QString::fromUtf8(QJsonDocument(stored).toJson(QJsonDocument::Compact))));    q.bindValue(":t", chatType);    q.bindValue(":p", peerId);    q.bindValue(":id", msgId);    q.exec();    pruneChat(chatType, peerId, 500);}QJsonArray LocalCache::loadMessages(const QString &chatType, int peerId, int limit){    QJsonArray arr;    if (!m_db.isOpen() || peerId <= 0) return arr;    QSqlQuery q(m_db);    q.prepare("SELECT msg_json FROM chat_cache WHERE chat_type=:t AND peer_id=:p "              "ORDER BY msg_id DESC LIMIT :lim");    q.bindValue(":t", chatType);    q.bindValue(":p", peerId);    q.bindValue(":lim", limit);    if (!q.exec()) return arr;    QList<QJsonObject> newest;    newest.reserve(limit);    while (q.next()) {        const QJsonObject o = QJsonDocument::fromJson(q.value(0).toString().toUtf8()).object();        if (!o.isEmpty()) newest.append(o);    }    for (int i = newest.size() - 1; i >= 0; --i)        arr.append(newest.at(i));    return arr;}voidLocalCache::pruneChat(const QString &chatType, int peerId, int keep){    if (!m_db.isOpen() || peerId <= 0 || keep <= 0) return;    QSqlQuery q(m_db);    q.prepare("SELECT COUNT(*) FROM chat_cache WHERE chat_type=:t AND peer_id=:p");    q.bindValue(":t", chatType);    q.bindValue(":p", peerId);    if (!q.exec() || !q.next()) return;    const int n = q.value(0).toInt();    if (n <= keep + 50) return;    const int drop = n - keep;    QSqlQuery del(m_db);    del.prepare("DELETE FROM chat_cache WHERE rowid IN ("                "SELECT rowid FROM chat_cache WHERE chat_type=:t AND peer_id=:p "                "ORDER BY msg_id ASC LIMIT :n)");    del.bindValue(":t", chatType);    del.bindValue(":p", peerId);    del.bindValue(":n", drop);    del.exec();}voidLocalCache::clearAll(){    if (m_db.isOpen()) {        m_db.close();    }    m_db = QSqlDatabase();    if (!m_connName.isEmpty()) {        QSqlDatabase::removeDatabase(m_connName);        m_connName.clear();    }    if (!m_dbPath.isEmpty()) {        QFile::remove(m_dbPath);        m_dbPath.clear();    }}
希望这篇文章能为您的C++ Qt开发等学习提供有价值的参考!感谢您的关注👉【Qt开发笔记】微信公众号,获取更多技术干货。

回首页,搜索你想要的文档

在首页搜索框输入关键词,快速定位资料

文库首页搜索指引 立即搜索

相关学习资料