Skip to content

Instantly share code, notes, and snippets.

@westonwatson
Created January 29, 2013 20:35
Show Gist options
  • Save westonwatson/4667543 to your computer and use it in GitHub Desktop.
Save westonwatson/4667543 to your computer and use it in GitHub Desktop.
node webSocket backend example
var sys = require('sys'),
http = require('http'),
io = require('socket.io'), // for npm, otherwise use require('./path/to/socket.io')
fs = require('fs');
var pageContent = ''; // content of the client page
// create web server and reply the client page on http request
var server = http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(pageContent);
});
// load client page content
fs.readFile('echo.html', function(err, content) {
if (err) throw err;
pageContent = content;
start();
});
// start web server
function start() {
server.listen(8000);
}
// connected clients
var clients = [];
// socket.io
var socket = io.listen(server);
socket.on('connection', function(client){
clients.push(client);
client.on('message', function(data) {
// broadcast the message to all clients
// this loop is the same as
// socket.broadcast(data);
for (var i in clients) {
clients[i].send(data);
}
});
client.on('disconnect', function() {
// remove client from the list
var index = clients.indexOf(client);
if (index != -1)
clients.splice(index, 1);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment