How can a QWebSocketServer identify messages from multiple HTML clients and answer each separately?



  • Refer to "Qt WebChannel Standalone Example"
    Step 1: setup the QWebSocketServer

        m_server = new QWebSocketServer("WebSocket app", QWebSocketServer::NonSecureMode, this);
        if (!m_server->listen(QHostAddress::LocalHost, 12345)) {
            qFatal("Failed to open web socket server, probabaly caused by an existing instance!");
            return;
        }
    

    Step 2: setup the channel

        m_channel = new QWebChannel(this);
    
        // setup the core and publish it to the QWebChannel
        m_channel->registerObject(QStringLiteral("core"), m_jsHelper);
        connect(m_server, SIGNAL(newConnection()), this, SLOT(newConnection()));
    

    Step 3: handle incoming socket

    void MainWindow::newConnection()
    {
        QWebSocket *socket = m_server->nextPendingConnection();
        QWebChannelAbstractTransport *t = new WebSocketTransport(socket);
        m_channel->connectTo(t);
        connect(t, SIGNAL(messageReceived(QJsonObject,QWebChannelAbstractTransport*)),
                this, SLOT(messageReceived(QJsonObject,QWebChannelAbstractTransport*)));
    }
    

    Step 4: open two browsers, both load same index.html, which contains a connection from C++ signal trigger to a JavaScript function:

                            core.sendText.connect(function(message) {// sendText is a C++ signal
                                output("Received message: " + message);
                            });
    

    In this way, one server emits one sendText message which will display in multiple browser clients.
    My question is each client can send its own question to the server, is there a way the server can answer each client separately and only?





  • Solved by 1) when a new client comes in, store WebSocketTransport in a list. 2) upon WebSocketTransport::textMessageReceived() trigger MainWindow::messageReceived() where indexing m_currentTransport. 3) Instead of sentText() use m_currentTransport->sendPlainTextMessage(text); to reply.

    Source code detail: git clone https://Lingfa@bitbucket.org/Lingfa/htmlchat.git


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.