一、安装服务端软件
npm install -S express express-ws --registry=https://registry.npm.taobao.org
二、服务端代码:
var express=require('express')
var expressWs=require('express-ws')
var app=express();
//让express具备websocket服务的能力
expressWs(app)
var fac=1000
app.ws('/ws',function (ws,req) {
let fd=setInterval(function () {
let x=Math.floor(Math.random()*fac)
ws.send(x+"")
},2000)
ws.on('message',function (msg) {
fac=parseInt(msg)
})
ws.on('close',function () {
clearInterval(fd)
})
})
// app.get("/ws",function (req,res) {
// res.send("Hello World")
// })
app.listen(9000);
三,客户端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="number"><button id="send">send</button>
<h1 id="rs"></h1>
<script>
var ws=new WebSocket("ws://localhost:9000/ws");
ws.onmessage=function (event) {
document.querySelector("#rs").innerHTML=event.data
}
document.querySelector("#send").addEventListener("click",function () {
let m=parseInt(document.querySelector("input").value)
ws.send(m+"");
})
</script>
</body>
</html>