Skip to content

Instantly share code, notes, and snippets.

@agektmr
Created August 6, 2012 09:28
Show Gist options
  • Save agektmr/3272625 to your computer and use it in GitHub Desktop.
Save agektmr/3272625 to your computer and use it in GitHub Desktop.
ws echo server
var WebSocket = require('ws').Server;
var ws = new WebSocket({port:8080});
var conn = [];
// Start accepting WebSocket connection
ws.on('connection', function(socket) {
// Add socket to list
conn.push(socket);
broadcast('1 peer connected.');
// When a message is received
socket.on('message', function(msg) {
broadcast(msg);
});
// When the connection is closed
socket.on('close', function() {
// remove socket from list
conn.forEach(function(connection, index) {
if (connection == socket) {
conn.splice(index, 1);
// broadcast other nodes that one is disconnected
broadcast('1 peer disconnected.');
return;
}
});
});
// When an error occurred
socket.on('error', function(e) {
console.log('Error: '+e.message);
});
});
// Broadcast a message
var broadcast = function(msg) {
conn.forEach(function(socket) {
socket.send(msg);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment