socket.io 實現簡單的用戶連接計數

/**
 * socket.io
 * 實現簡單的打開瀏覽器/關閉瀏覽器記錄信息
 */
var http = require('http'), // 加載http模塊
    fs = require('fs'), // 加載fs模塊
    count = 0; // 計數
// 創建web服務器
var server = http.createServer(function (req, res) {
    // 讀取index.html
    fs.readFile('./index.html', function(error, data) {
        // 發送頭信息
        res.writeHead(200, {'Content-type': 'text/html;charset=utf-8'});
        // 輸出index.html的內容到客戶端
        res.end(data, 'utf-8');
    });
}).listen(3000); // 運行在3000端口上
// 打印運行日誌信息
console.log('Server running!');
// 加載socket.io模塊,綁定到已經創建的server
var ios = require('socket.io').listen(server);
// 監聽 connection 事件
ios.sockets.on('connection', function(socket) {
    console.log("用戶登錄了");
    // 用戶打開連接 count++
    count++;
    // 打開新的連接顯示的內容
    socket.emit('users', {number: count});
    // 顯示數據到已經打開的連接上
    socket.broadcast.emit('users', {number: count});
    // 監聽 disconnection 事件
    socket.on('disconnect', function() {
        //用戶關閉count--
        count--;
        console.log("用戶退出了");
        // 顯示數據到已經打開的連接上
        socket.broadcast.emit('users', {number: count});
    })
});
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<h1>Socket.IO Example</h1>
<h2 id="msg" style="color: red;"></h2>
<script src="/socket.io/socket.io.js"></script>
<script src="http://uil.fanna.com.cn/jquery/jquery-1.7.1.min.js" type="text/javascript"></script>
<script>
    var socket = io.connect("http://127.0.0.1:3000");
    socket.on('users', function(data) {
        $('#msg').html(("當前有" + data.number+"個用戶登錄"));
    })
</script>
</body>
</html>








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章