Skip to content

Instantly share code, notes, and snippets.

@luk- luk-/index.html

Created Oct 30, 2011
Embed
What would you like to do?
Broadcasting with socket.io
<!DOCTYPE html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('/');
socket.on('bc', function (data) {
console.log(data);
window.document.write(data.bc + '<br />');
});
socket.on('dc', function (data) {
console.log(data);
window.document.write(data.bc + '<br />');
});
</script>
</head>
<body></body>
</html>
var app = require('http').createServer(handler);
var io = require('socket.io').listen(app);
var fs = require('fs');
app.listen(80);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error 500');
}
res.writeHead(200);
res.end(data);
});
}
var users_connected = {
base: 0,
_add: function (callback)
{
this.base++;
callback(this.base);
},
_sub: function (callback)
{
this.base--;
callback(this.base);
}
}
io.sockets.on('connection', function (socket) {
users_connected._add(function(num){
socket.broadcast.emit('bc', { bc: num });
});
socket.on('disconnect', function () {
users_connected._sub(function(num){
socket.broadcast.emit('dc', { bc: num });
});
});
});
@luk-

This comment has been minimized.

Copy link
Owner Author

luk- commented Oct 30, 2011

This is a simple example of how socket.io's broadcasting feature functions. Each time an instance of the page is opened or closed on a global level (after the first), it's written to the page.

Example: luk.no.de

Try opening up multiple instances of the page, then watch the first while you close the other tabs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.