サーバー ( node.js WSを使用して実装) が接続されているすべてのユーザーを追跡し、受信した各メッセージをブロードキャストする、 HTML5 WebSocketテクノロジに基づく非常に単純なチャット アプリケーションを作成しています。一方、クライアントはサーバーに接続し、ユーザーのアクションに従ってメッセージをサーバーに送信します。
私が観察している問題は、接続を開いた後にサーバーがクライアントにメッセージを送信しない限り、Google Chrome で実行されているクライアントから送信されたすべてのメッセージが、いくつかのメッセージが送信されるまでバッファリングされることです。バッファがいっぱいになると、すべてのメッセージが一度に送信されます。これにより、エンド ユーザーにとって非常に反応の悪いチャット エクスペリエンスが作成されます。
私が見つけた修正はws.send("Hello Client:" + clientId);
、サーバー側で接続を開いた後にシングルを追加することでしたが、なぜこれが必要なのかわかりませんか? 以下に、私のクライアントおよびサーバー コンポーネントのスニペットを示しますが、ソース コード全体はChatMate git projectで入手できます。
サーバーコード:
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);
};
}
ありがとう!