什么是 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); }); });
客户端代码:
怎么用 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)