public
Created

  • Download Gist
gistfile1.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
var sys = require("sys"),
ws = require("./ws");
 
Array.prototype.remove = function(e) {
for (var i = 0; i < this.length; i++)
if (e == this[i]) return this.splice(i, 1);
}
 
var clients = [];
 
ws.createServer(function (websocket) {
clients.push(websocket);
 
websocket.addListener("connect", function (resource) {
// emitted after handshake
sys.debug("connect: " + resource);
 
// server closes connection after 10s, will also get "close" event
//setTimeout(websocket.end, 10 * 1000);
}).addListener("data", function (data) {
// handle incoming data
 
// send data to client
clients.forEach(function (client) {
if (client != websocket) {
sys.puts('write...');
try {
client.write(data);
} catch (e) {
clients.remove(client);
}
}
});
}).addListener("close", function () {
// emitted when server or client closes connection
sys.debug("close");
clients.remove(websocket);
});
}).listen(8000);

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.