nodejs+socket.io.js

来源:互联网 发布:c语言课程设计报告 编辑:程序博客网 时间:2024/05/17 07:13
(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>

0 0