Created
October 30, 2011 00:14
-
-
Save luk-/1325282 to your computer and use it in GitHub Desktop.
Broadcasting with socket.io
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
<!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> |
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 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 }); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.