Zor*_*ayr 5 javascript html5 google-chrome websocket
我正在编写一个基于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);
}
}
}
});
});
Run Code Online (Sandbox Code Playgroud)
客户代码:
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);
};
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
| 归档时间: |
|
| 查看次数: |
2479 次 |
| 最近记录: |