5

我正在编写一个基于HTML5 WebSocket技术的非常简单的聊天应用程序,其中服务器(使用node.js WS实现)跟踪所有连接的用户并广播每条收到的消息。另一方面,客户端连接到服务器并根据用户的操作向服务器发送消息。

我观察到的问题是,除非服务器在打开连接后向客户端发送消息,否则从在 Google Chrome 上运行的客户端发送的所有消息都会被缓冲,直到发送了几条消息。一旦缓冲区已满,所有消息都会立即发送。这为最终用户创造了一种非常无响应的聊天体验。

我发现的修复是ws.send("Hello Client:" + clientId);在服务器端打开连接后添加单个,但我不确定为什么这是必要的?您可以在下面找到我的客户端和服务器组件的片段,但完整的源代码可在ChatMate git 项目中找到。

服务器代码:

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's 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);
                }
            }

        }
    });
});

客户代码

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);
    };

}

谢谢!

4

0 回答 0