1、新建文件夾
2、文件夾中新建index.html 和 index.js
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div class="contain"> <div class="item"> <h5>A1</h5> <span>100</span>元 </div> <div class="item"> <h5>B2</h5> <span>100</span>元 </div> <div class="item"> <h5>C3</h5> <span>100</span>元 </div> <div class="item"> <h5>D4</h5> <span>100</span>元 </div> <div class="item"> <h5>E5</h5> <span>100</span>元 </div> <button>close</button> </div> <script> var mess = document.querySelector('.contain'); if(window.WebSocket){ var ws = new WebSocket("ws://localhost:8006") document.querySelector('button').onclick = function(){ ws.close(); } ws.onopen = function () { ws.send('getPrice'); } ws.onclose = function () { ws.close(); } ws.onerror = function () { ws.close(); } ws.onmessage = function (e) { var data = JSON.parse(e.data); var arr = []; data.current.forEach((value)=>{ arr.push(`<div class="item"><h5>${value.id}</h5><span>${value.price}</span>元</div>`) }) mess.innerHTML = arr.join(''); } } </script> </body> </html>
index.js
var ws = require('nodejs-websocket'); var pubSub = { subscribe:[], addPub(coon){ this.subscribe.push(coon) }, pubInfo(data){ this.subscribe.forEach((value)=>{ console.log(value) value.sendText(data); }) } } var serve = ws.createServer(function (coon) { coon.on('text',function (str) { if(str == "getPrice"){ // console.log(coon); pubSub.addPub(coon) } }) coon.on('close',function () { console.log('close') }) coon.on('error',function (code) { console.log('error') }) }).listen(8006) function _RandNum() { return Math.ceil(Math.random() * 100); } function getData() { return JSON.stringify({"current":[ { id:"A1", price:_RandNum() }, { id:"B2", price:_RandNum() }, { id:"C3", price:_RandNum() }, { id:"D4", price:_RandNum() }, { id:"E4", price:_RandNum() } ]}) } setInterval(()=>{ pubSub.pubInfo(getData()); },2000)
3、文件夾下右鍵 open in Terminal ,安裝 nodejs-websocket
npm install nodejs-websocket
目錄下多了文件夾:node_modules
4、在Terminal運行 node index.js
打開頁面即可實現頁面實時刷新數據。