Created
August 6, 2012 09:28
-
-
Save agektmr/3272625 to your computer and use it in GitHub Desktop.
ws echo server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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