WebSocket server example#

A sample WebSocket server echoing back messages sent to it.

Description#

The echoserver example implements a WebSocket server that echoes back everything that is sent to it.

Code#

We start by creating a QWebSocketServer (`new QWebSocketServer()`). After the creation, we listen on all local network interfaces (` Any `) on the specified port.

def __init__(self, port, debug, parent):
    QObject(parent),
    m_pWebSocketServer(QWebSocketServer(QStringLiteral("Echo Server"),
                                            QWebSocketServer.NonSecureMode, self)),
    m_debug(debug)

    if (m_pWebSocketServer.listen(QHostAddress.Any, port)) {
        if (m_debug)
            print("Echoserver listening on port", port)
        connect(m_pWebSocketServer, QWebSocketServer.newConnection,
                self, EchoServer::onNewConnection)
        connect(m_pWebSocketServer, QWebSocketServer.closed, self, EchoServer.closed)

If listening is successful, we connect the `newConnection()` signal to the slot `onNewConnection()`. The `newConnection()` signal will be thrown whenever a new WebSocket client is connected to our server.

def onNewConnection(self):

    pSocket = m_pWebSocketServer.nextPendingConnection()
    connect(pSocket, QWebSocket.textMessageReceived, self, EchoServer.processTextMessage)
    connect(pSocket, QWebSocket.binaryMessageReceived, self, EchoServer.processBinaryMessage)
    connect(pSocket, QWebSocket.disconnected, self, EchoServer.socketDisconnected)
    m_clients << pSocket

When a new connection is received, the client QWebSocket is retrieved (`nextPendingConnection()`), and the signals we are interested in are connected to our slots (`textMessageReceived()`, `binaryMessageReceived()` and `disconnected()`). The client socket is remembered in a list, in case we would like to use it later (in this example, nothing is done with it).

def processTextMessage(self, message):

    pClient = QWebSocket (sender())
    if (m_debug)
        print("Message received:", message)
    if (pClient) {
        pClient.sendTextMessage(message)

Whenever `processTextMessage()` is triggered, we retrieve the sender, and if valid, send back the original message (`sendTextMessage()`). The same is done with binary messages.

def processBinaryMessage(self, message):

    pClient = QWebSocket (sender())
    if (m_debug)
        print("Binary Message received:", message)
    if (pClient) {
        pClient.sendBinaryMessage(message)

The only difference is that the message now is a QByteArray instead of a QString .

def socketDisconnected(self):

    pClient = QWebSocket (sender())
    if (m_debug)
        print("socketDisconnected:", pClient)
    if (pClient) {
        m_clients.removeAll(pClient)
        pClient.deleteLater()

Whenever a socket is disconnected, we remove it from the clients list and delete the socket. Note: it is best to use `deleteLater()` to delete the socket.