Skip to content

Instantly share code, notes, and snippets.

@remy
Created June 9, 2010 12:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save remy/431369 to your computer and use it in GitHub Desktop.
Save remy/431369 to your computer and use it in GitHub Desktop.
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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment