qt cmake项目使用websocket实现简单的聊天

本文详细解读了一个使用Qt库创建的WebSocket聊天服务器的C++代码,包括CMakeLists.txt配置、ChatServer类的实现以及配合HTML网页实现的简单聊天室功能。
摘要由CSDN通过智能技术生成

解析一下qt示例程序

Cmakelist.txt文件添加:

find_package(Qt6 REQUIRED COMPONENTS WebSockets)
target_link_libraries(mytarget PRIVATE Qt6::WebSockets)

定义chatserver类

头文件

#ifndef CHATSERVER_H
#define CHATSERVER_H

#include <QtCore/QObject>
#include <QtCore/QList>

QT_FORWARD_DECLARE_CLASS(QWebSocketServer)
QT_FORWARD_DECLARE_CLASS(QWebSocket)
QT_FORWARD_DECLARE_CLASS(QString)

class ChatServer : public QObject
{
    Q_OBJECT
public:
    explicit ChatServer(quint16 port, QObject *parent = nullptr);
    ~ChatServer() override;

private slots:
    void onNewConnection();
    void processMessage(const QString &message);
    void socketDisconnected();

private:
    QWebSocketServer *m_pWebSocketServer;
    QList<QWebSocket *> m_clients;
};

#endif //CHATSERVER_H

实现:

#include "chatserver.h"

#include <QtWebSockets>
#include <QtCore>

#include <cstdio>
using namespace std;

QT_USE_NAMESPACE //qt宏,用于声明使用Qt命名空间,这样就不用写Qt::了

static QString getIdentifier(QWebSocket *peer)
{
    return QStringLiteral("%1:%2").arg(peer->peerAddress().toString(),
                                       QString::number(peer->peerPort()));
}

ChatServer::ChatServer(quint16 port, QObject *parent) :
    QObject(parent),
    m_pWebSocketServer(new QWebSocketServer(QStringLiteral("Chat Server"),
                                            QWebSocketServer::NonSecureMode,
                                            this))
{
    if (m_pWebSocketServer->listen(QHostAddress::Any, port))
    {
        QTextStream(stdout) << "Chat Server listening on port " << port << '\n';
        connect(m_pWebSocketServer, &QWebSocketServer::newConnection,
                this, &ChatServer::onNewConnection);
    }
}

ChatServer::~ChatServer()
{
    m_pWebSocketServer->close();
}

void ChatServer::onNewConnection()//
{
    auto pSocket = m_pWebSocketServer->nextPendingConnection();
    QTextStream(stdout) << getIdentifier(pSocket) << " connected!\n";
    pSocket->setParent(this);// 设置新创建的 QWebSocket 对象的父对象为当前 ChatServer 实例。这样在 ChatServer 实例被销毁时,其所有子对象,包括这些 QWebSocket 对象,也会被销毁。

    connect(pSocket, &QWebSocket::textMessageReceived,
            this, &ChatServer::processMessage);
    connect(pSocket, &QWebSocket::disconnected,
            this, &ChatServer::socketDisconnected);

    m_clients << pSocket;
}

void ChatServer::processMessage(const QString &message)
{
    QWebSocket *pSender = qobject_cast<QWebSocket *>(sender());
    for (QWebSocket *pClient : std::as_const(m_clients)) { //std::as_const() 函数返回一个只读的引用,以避免对容器进行修改,c++17语法
        if (pClient != pSender) //如果消息的发送者不是当前的客户端,就把消息发送给其他客户端
            pClient->sendTextMessage(message);
    }
}

void ChatServer::socketDisconnected()
{
    QWebSocket *pClient = qobject_cast<QWebSocket *>(sender());
    QTextStream(stdout) << getIdentifier(pClient) << " disconnected!\n";
    if (pClient)
    {
        m_clients.removeAll(pClient);
        pClient->deleteLater();
    }
}


main函数:

#include <QtCore/QCoreApplication>

#include "chatserver.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    ChatServer server(1234);

    return a.exec();
}

运行后,聊天服务运行在本地1234端口上

配合html网页实现一个简单的聊天室:
在这里插入图片描述
这里只简单体现过程。

html文件源码:

<html>
    <head>
        <title>WebSocket Chat Client</title>
    </head>
    <body>
        <h1>WebSocket Chat Client</h1>
        <p>
            Host: <input id="webSocketHost" type="text" value="localhost:1234"/>
        </p>
        <p>
            <button onClick="initWebSocket();">Connect</button>
            <button id="disconnectButton" onClick="stopWebSocket();" disabled>Disconnect</button>
            <button onClick="checkSocket();">State</button>
        </p>
        <p>
            <textarea id="debugTextArea" style="width:400px;height:200px;" readonly></textarea>
        </p>
        <p>
            <input type="text" id="inputNick" value="nickname" />
            <input type="text" id="inputText" onkeydown="if(event.keyCode==13)sendMessage();"/>
            <button id="sendButton" onClick="sendMessage();" disabled>Send</button>
        </p>

        <script type="text/javascript">
            var debugTextArea = document.getElementById("debugTextArea");
            function debug(message) {
                debugTextArea.value += message + "\n";
                debugTextArea.scrollTop = debugTextArea.scrollHeight;
            }

            function sendMessage() {
                var nickname = document.getElementById("inputNick").value;
                var msg = document.getElementById("inputText").value;
                var strToSend = nickname + ": " + msg;
                if ( websocket != null )
                {
                    document.getElementById("inputText").value = "";
                    websocket.send( strToSend );
                    console.log( "string sent :", '"'+strToSend+'"' );
                    debug(strToSend);
                }
            }

            var websocket = null;

            function initWebSocket() {
                try {
                    if (typeof MozWebSocket == 'function')
                        WebSocket = MozWebSocket;
                    if ( websocket && websocket.readyState == 1 )
                        websocket.close();
                    var wsUri = "ws://" + document.getElementById("webSocketHost").value;
                    websocket = new WebSocket( wsUri );
                    websocket.onopen = function (evt) {
                        debug("CONNECTED");
                        document.getElementById("disconnectButton").disabled = false;
                        document.getElementById("sendButton").disabled = false;
                    };
                    websocket.onclose = function (evt) {
                        debug("DISCONNECTED");
                        document.getElementById("disconnectButton").disabled = true;
                        document.getElementById("sendButton").disabled = true;
                    };
                    websocket.onmessage = function (evt) {
                        console.log( "Message received :", evt.data );
                        debug( evt.data );
                    };
                    websocket.onerror = function (evt) {
                        debug('ERROR: ' + evt.data);
                    };
                } catch (exception) {
                    debug('ERROR: ' + exception);
                }
            }

            function stopWebSocket() {
                if (websocket)
                    websocket.close();
            }

            function checkSocket() {
                if (websocket != null) {
                    var stateStr;
                    switch (websocket.readyState) {
                        case 0: {
                            stateStr = "CONNECTING";
                            break;
                        }
                        case 1: {
                            stateStr = "OPEN";
                            break;
                        }
                        case 2: {
                            stateStr = "CLOSING";
                            break;
                        }
                        case 3: {
                            stateStr = "CLOSED";
                            break;
                        }
                        default: {
                            stateStr = "UNKNOW";
                            break;
                        }
                    }
                    debug("WebSocket state = " + websocket.readyState + " ( " + stateStr + " )");
                } else {
                    debug("WebSocket is null");
                }
            }
        </script>
    </body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值