nodejs+socket.io.js

(2013-07-04 16:08:47)
转载
标签: 

nodejs

 

socket.io

分类: nodejs
app.js
var app = require('http').createServer(handler)
   , io = require('socket.io').listen(app)
   , fs = require('fs')

app.listen(8000);

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);
   });
}

io.sockets.on('connection', function (socket) {
   socket.emit('news', { hello: 'world' });
   socket.on('my other event', function (data) {
       console.log(data);
   });
});
index.html
<script src="http://localhost:8000/socket.io/socket.io.js"></script>
<script>
   var socket = io.connect('http://localhost:8000');
   socket.on('news', function (data) {
       alert(data["hello"]);
       socket.emit('my other event', { my: 'data' });
   });
</script>

你可能感兴趣的:(nodejs+socket.io.js)