前言
本文實作一個簡易的即時訪客人數計算器,不會使用到資料庫。
後端
初始化專案。
安裝 ws
依賴套件。
新增 main.js
檔:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| const { WebSocketServer } = require('ws');
const wss = new WebSocketServer({ port: 8080, });
const origins = new Map();
wss.on('connection', (ws, req) => { const { origin } = req.headers;
origins.set(origin, origins.get(origin) + 1 || 1);
const timer = setInterval(() => { ws.send(JSON.stringify({ count: origins.get(origin), })); }, 1000);
ws.on('message', () => { });
ws.on('close', () => { clearInterval(timer); origins.get(origin) > 1 ? origins.set(origin, origins.get(origin) - 1) : origins.delete(origin); }); });
|
前端
新增 index.html
檔:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="counter"></div> <script> const ws = new WebSocket('ws://localhost:8080'); ws.onmessage = (e) => { const { count } = JSON.parse(e.data); document.getElementById("counter").innerText = `Visitor Count: ${count}`; }; </script> </body> </html>
|
使用 Live Server 預覽。
瀏覽網頁
前往 http://127.0.0.1:8080 瀏覽。