I would like to use websockets to send updates from the server to the clients.
I know I can use Server Sent Events but Internet Explorer doesn't have great compatibility with it so I prefer to use websocket.
The TotalJs WebSocket allow me to use it like a client?
I'm trying to do this: (TotalJs Websocket Example)
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);
});
}
When someone connect to http://127.0.0.1/send all clients connected to the server will receive a message.
Node.js doesn't have native WebSocket support so the send_message() function does not work. I would like to use TotalJs Websocket support but I don't know how to use it like a client.
Thats it.
Thank you very much.