首先我們需要安裝socket模塊
安裝命令: npm install socket.io
編輯前臺頁面:index.html
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>統計在線人數</title> <script src="http://localhost:3000/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');
});
啓動web服務器,訪問index.html:
再打開一個窗口打開這個鏈接:
服務端打印日誌信息:
node 的socket.io模塊使用起來非常簡單方便,把我們需要交互的實時信息推送到前端的頁面。