WebSocket简介:
如果要实现服务端主动发送消息到前端,使用axios(基于http)就得被迫轮询,也就是隔一段时间就向服务器发送一次请求。轮询的缺点:效率低、浪费资源(因为必须不停的连接,或者http连接始终打开)。解决这个问题最好的方式就是WebSocket。
安装依赖:
yarn add express express-ws nodemen
package.json
{
"name": "ws",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start":"nodemon app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2",
"express-ws": "^5.0.2",
"nodemon": "^2.0.20"
}
}
//nodemon 保持服务端持续连接实现热更新
Express中间件
app.js
//引入框架
const express= require("express")
const app =express();
//注入express-ws
const expressWs = require("express-ws")
const websocket = require("./websocket.js")
const port = 3000
expressWs(app)
//中间件
app.use("/cat",express.static('public/cat.html'))
app.use("/dog",express.static('public/dog.html'))
app.use('/ws',websocket)
app.use(express.static('public'))
//当服务器找不到页面不做任何操作
app.get("/*",(req,res)=>{})
//监听端口
app.listen(port,()=>{
console.log(`Server is running at http://localhost:${port}`);
})
WebSocket路由匹配
websocket.js
const express = require("express")
const expressWs = require("express-ws")
const router = express.Router()
expressWs(router)
router.ws("/dog",ws=>{
//send发射数据
// ws.send("dog连接成功")
//接受客户端发来的数据
ws.on("message",(msg)=>{
//把数据返回给客户端
ws.send(msg)
})
})
module.exports=router
客户端websocket方法
<script>
//实例化WebSocket 连接服务端
const ws = new WebSocket("ws://localhost:3000/ws/dog")
ws.onmessage = function (res) {
//获取数据
// console.log(res.data);
msgbox.innerHTML += rightMsgFn(res.data)
//添加滚动
msgbox.scrollTo({
top: msgbox.scrollHeight,
behavior: "smooth"
})
}
ws.onopen = function () {
//值为1代表连接成功
// console.log(ws.readyState);
}
// ws.onmessage = function (res) {
// //获取数据
// console.log(res.data);
// }
ws.onclose = function () {
console.log('连接已断开');
}
ws.onerror = function () {
console.log('连接错误');
}
</script>