安装 淘宝镜像 npm install express --registry=https://registry.npm.taobao.org
var app = require('http').createServer(handler), io = require('socket.io').listen(app), fs = require('fs')app.listen(8080); io.set('log level', 1);//将socket.io中的debug信息关闭 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, {'Content-Type': 'text/html'}); res.end(data); }); } io.sockets.on('connection', function (socket) { socket.emit('news', { hello: 'world' }); socket.on('my other event', function (data) { console.log(data); }); });
客户端
<script type="text/javascript" src="http://localhost:8080/socket.io/socket.io.js"></script> <script type="text/javascript"> var socket = io.connect('http://localhost:8080'); socket.on('news', function (data) { alert(data.hello); socket.emit('my other event', { my: 'data' }); }); </script>