HTML5 WebSocket: Client Messages Buffered in Google Chrome 22

I am writing a very simple chat application based on HTML5 WebSocket technology , where the server (implemented using node.js WS ) monitors all connected users and broadcasts every message received. The client, on the other hand, connects to the server and, in accordance with the actions of the user, sends messages to the server.

The problem that I am observing is that if the server does not send a message to the client after opening the connection, all messages sent from the client running in Google Chrome will be buffered until several messages are sent. When the buffer is full, all messages are sent immediately. This creates a very insecure chat for the end user.

The fix I discovered was to add one ws.send("Hello Client:" + clientId);after opening the connection on the server side, but I'm not sure why this is necessary? Below you can find a snippet from my client and server components, but all the source code is available in the ChatMate git project .

Server Code:

wsServer.on('connection', function (ws) {
    var clientId = nextClientId += 1;
    clients[clientId] = ws;
    log("Accepted connection from client " + clientId + ".");

    //The fix: If you emit this initial message from the server, then
    //all of client messages will be cached. 
    ws.send("Hello Client: " + clientId);

    ws.on('message', function (message) {
        log("Received message: " + message);
        var id;
        for (id in clients ) {
            if (clients.hasOwnProperty(id)) {
                if (parseInt(id, 10) !== clientId) {
                    clients[id].send(message);
                }
            }

        }
    });
});

Customer Code :

function WebSocketTest() {
    "use strict";
    ws = new WebSocket("ws://DOMAIN:8080/");

    ws.onopen = function () {
        console.log("Connection is open.");
        //This message will not be sent if the server does not send 
        //a message first.
        ws.send("Client Message.");
    };

    ws.onmessage = function (e) {
        console.log("Message is received: " + e.data);
    };

}

Thank!

+5
source

All Articles