#### 安装socket.io ~~~ npm install socket.io ~~~ #### Node http server 使用方法 服务器端代码(app.js) ~~~ var app = require('http').createServer(handler) var io = require('socket.io')(app); var 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.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('http://localhost'); socket.on('news', function (data) { console.log(data); socket.emit('my other event', { my: 'data' }); }); </script> ~~~ #### Express 3/4使用方法 服务器端代码(app.js) ~~~ var app = require('express')(); var server = require('http').Server(app); var io = require('socket.io')(server); server.listen(80); app.get('/', function (req, res) { res.sendfile(__dirname + '/index.html'); }); io.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> ~~~ #### Express 2.x使用方法 服务器端代码(app.js) ~~~ var app = require('express').createServer(); var io = require('socket.io')(app); app.listen(80); app.get('/', function (req, res) { res.sendFile(__dirname + '/index.html'); }); io.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> ~~~