介绍一下node.js模块之socket IO
发布于 11 年前 作者 lzxue 17492 次浏览 最后一次编辑是 8 年前

什么是 Socket.IO? Socket.IO的为了在浏览器和移动设备上创建实时应用而产生的,它可以模糊不同传输机制之间的差异。server端代码: var io = require(‘socket.io’).listen(80);

  io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
    socket.on('my other event', function (data) {
     console.log(data);
     });
   });

客户端代码: <script src="/socket.io/socket.io.js"></script> <script> var socket = io.connect(‘http://localhost’); socket.on(‘news’, function (data) { console.log(data); socket.emit(‘my other event’, { my: ‘data’ }); }); </script>

怎么用 socket.io 安装 npm install socket.io 利用Node http server 模块 对于这个例子,简单的使用“npm install socket.io” 服务端(app.js) var app = require(‘http’).createServer(handler) , io = require(‘socket.io’).listen(app) , 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 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="/socket.io/socket.io.js"></script> <script> var socket = io.connect(‘http://localhost’); socket.on(‘news’, function (data) { console.log(data); socket.emit(‘my other event’, { my: ‘data’ }); }); </script>

2 回复

你就把首页的example copy一下无任何原创有意思吗?

的确… 楼主, 大部分论坛上的看文档的能力还是有的 我们整理一下 Wiki 之后大概需要对一些文档进行粗略翻译, 希望加入

回到顶部