Socket.io: some starter examples
There not being much easy to use documentation, and the existing tutorials being out of date, here is some code that works as of today
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
$("#test").text(data.hello);
socket.emit('my other event', { my: 'data' });
});
</script>
<div id="test"></div>
</body>
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
, url = require('url');
app.listen(8001);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
function handler2(request, response) {
console.log('Connection');
var path = url.parse(request.url).pathname;
switch(path){
case '/':
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('hello world Simon');
response.end();
break;
default:
fs.readFile(__dirname + path, function(error, data){
if (error){
response.writeHead(404);
response.write("oops file doesn't exist - 404");
}
else{
response.writeHead(200, {"Content-Type": "text/html"});
response.write(data, "utf8");
}
response.end();
});
break;
};
}
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});