【发布时间】:2015-07-03 08:10:37
【问题描述】:
我想使用 websockets 将更新从服务器发送到客户端。
我知道我可以使用服务器发送事件,但 Internet Explorer 与它的兼容性不是很好,所以我更喜欢使用 websocket。
TotalJs WebSocket 允许我像客户端一样使用它吗?
我正在尝试这样做:(TotalJs Websocket 示例)
exports.install = function(framework) {
framework.route('/');
framework.route('/send/', send_message);
framework.websocket('/', socket_homepage, ['json']);
};
function send_message() {
var controller = this;
var socket = new WebSocket('ws://127.0.0.1:8000/');
socket.onopen = function() {
socket.send(encodeURIComponent(JSON.stringify({ message: "send_message" })));
};
socket.close();
socket = null;
}
function socket_homepage() {
var controller = this;
controller.on('open', function(client) {
console.log('Connect / Online:', controller.online);
client.send({ message: 'Hello {0}'.format(client.id) });
controller.send({ message: 'Connect new user: {0}\nOnline: {1}'.format(client.id, controller.online) }, [], [client.id]);
});
controller.on('close', function(client) {
console.log('Disconnect / Online:', controller.online);
controller.send({ message: 'Disconnect user: {0}\nOnline: {1}'.format(client.id, controller.online) });
});
controller.on('message', function(client, message) {
console.log(message);
if (typeof(message.username) !== 'undefined') {
var old = client.id;
client.id = message.username;
controller.send({ message: 'rename: ' + old + ', new: ' + client.id });
return;
}
// send to all without this client
message.message = client.id + ': ' + message.message;
console.log(message);
controller.send(message);
});
}
当有人连接到http://127.0.0.1/send时,所有连接到服务器的客户端都会收到一条消息。
Node.js 没有原生 WebSocket 支持,因此 send_message() 函数不起作用。我想使用 TotalJs Websocket 支持,但我不知道如何像客户端一样使用它。
就是这样。
非常感谢。
【问题讨论】:
-
我对 total.js 不熟悉,但您是否看过文档中的示例:docs.totaljs.com/v1.8.x/…
-
现在试过了,但我认为 controller.send() 仅在我们使用“framework.websocket”路由并且我使用“framework.route”时才存在。我试过“console.log(controller.send);”在 send_message() 函数中,我收到“未定义”。非常感谢。
标签: javascript node.js total.js