nodejs 使用socket.io与网页实时数据交互
首先我们需要安装socket模块
安装命令: npm install socket.io
编辑前台页面:index.html
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>统计在线人数</title> <script src="/socket.io/socket.io.js"></script> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript"> // 创建websocket连接 var socket = io.connect('http://localhost:3000'); // 把信息显示到div上 socket.on('onlinenums', function (data) { $("#nums").html(data.nums); }); </script> </head> <body> 当前在线人数:<span style="color: red;" id="nums">0</span> </body> </html>
服务端的:index.js
volatile 意思大概是说,当服务器发送数据时,客户端因为各种原因不能正常接收,比如网络问题、或者正处于长连接的建立连接阶段。此时会让我们的应用变得 suffer,那就需要考虑发送 volatile 数据。
var app = require('http').createServer(handler), io = require('socket.io').listen(app), fs = require('fs'); //当前在线人数 var onlineCount = 0; 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) { console.log('有新用户进入...'); //叠加当前在线人数 onlineCount++; var tweets = setInterval(function () { socket.volatile.emit('onlinenums', {nums : onlineCount}); }, 1000); console.log('当前用户数量:'+onlineCount); //客户端断开连接 socket.on('disconnect', function() { if(onlineCount > 0 ){ //当前在线用户减一 onlineCount--; console.log('当前用户数量:'+onlineCount); } }); }); //启动HTTP服务,绑定端口3000 app.listen(3000, function(){ console.log('listening on *:3000'); });
运行index.js:
启动web服务器,访问index.html:
node 的socket.io模块使用起来非常简单方便,把我们需要交互的实时信息推送到前端的页面。