本页内容

WebSocket 服务器示例

描述

echoserver 示例实现了一个 WebSocket 服务器,该服务器会将收到的所有数据原样回传。

代码

首先,我们创建一个QWebSocketServer (`new QWebSocketServer()`)。创建完成后,我们监听所有本地网络接口(`QHostAddress::Any`)上指定的port 。

EchoServer::EchoServer(quint16 port, booldebug,QObject*parent) :
    QObject(parent),
    m_pWebSocketServer(newQWebSocketServer(QStringLiteral("Echo Server"),
                                            QWebSocketServer::NonSecureMode, this)),
    m_debug(debug)
{
    if(m_pWebSocketServer->listen(QHostAddress::Any,port)) {
        if(m_debug)
            qDebug() << "Echoserver listening on port" << port;
        connect(m_pWebSocketServer, &QWebSocketServer::newConnection,
                this, &EchoServer::onNewConnection);
        connect(m_pWebSocketServer, &QWebSocketServer::closed, this, &EchoServer::closed);
    }
}

如果监听成功,我们将 `newConnection()` 信号与槽 `onNewConnection()` 关联。每当有新的 WebSocket 客户端连接到我们的服务器时,都会触发 `newConnection()` 信号。

void EchoServer::onNewConnection()
{
    QWebSocket *pSocket = m_pWebSocketServer->nextPendingConnection();

    connect(pSocket, &QWebSocket::textMessageReceived, this, &EchoServer::processTextMessage);
    connect(pSocket, &QWebSocket::binaryMessageReceived, this, &EchoServer::processBinaryMessage);
    connect(pSocket, &QWebSocket::disconnected, this, &EchoServer::socketDisconnected);

    m_clients << pSocket;
}

当接收到新连接时,会获取客户端QWebSocket (通过 `nextPendingConnection()`),并将我们感兴趣的信号连接到相应的槽(`textMessageReceived()`、`binaryMessageReceived()` 和 `disconnected()`)。 客户端套接字会被保存在一个列表中,以便日后可能需要使用(在本例中,并未对其进行任何处理)。

voidEchoServer::processTextMessage(QString message)
{
    QWebSocket*pClient =qobject_cast<QWebSocket*>(sender());
    if(m_debug)
        qDebug() << "Message received:" << message;
   if(pClient) {
        pClient->sendTextMessage(message);
    }
}

每当触发 `processTextMessage()` 时,我们会获取发件人信息,如果有效,则将原始消息发送回去(`sendTextMessage()`)。对于二进制消息,处理方式也相同。

voidEchoServer::processBinaryMessage(QByteArray message)
{
    QWebSocket*pClient =qobject_cast<QWebSocket*>(sender());
    if(m_debug)
        qDebug() << "Binary Message received:" << message;
   if(pClient) {
        pClient->sendBinaryMessage(message);
    }
}

唯一的区别在于,消息现在是 `QByteArray `,而不是 `QString`。

voidEchoServer::socketDisconnected()
{
    QWebSocket*pClient =qobject_cast<QWebSocket*>(sender());
    if(m_debug)
        qDebug() << "socketDisconnected:" << pClient;
   if(pClient) {
        m_clients.removeAll(pClient);
        pClient->deleteLater();
    }
}

每当套接字断开连接时,我们会将其从客户端列表中移除,并删除该套接字。注意:最好使用 `deleteLater()` 来删除套接字。

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.