nodejs后端代码 server.js
//需要安装ws模块 npm install ws
const WebSocket = require("ws")
const port = 8085const ws = new WebSocket.Server({port})ws.on("connection", (socket) => {socket.on("message",(message) => {const data = JSON.parse(message.toString('utf-8'))if(data.type === 'heart') {socket.send("收到心跳")} else {socket.send(`你发来的类型是${data.type}`)}})socket.on("close", () => {socket.send("close")})
})
console.log(`server start at ${port}`)
直接在文件所在目录打开cmd窗口,启动服务: node server.js
浏览器端 index.html
<!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><button type="button" onclick="sendWs()">发送消息</button><button type="button" onclick="closeWs()">关闭链接</button><div>发送第<span id="count"></span>次心跳</div>
</body>
</html>
<script>
const ws = new WebSocket("ws://localhost:8085");
let count = 0
const interval = setInterval(() => {count++ws.send(JSON.stringify({type:'heart'}))document.getElementById("count").innerHTML = count}, 1000)const sendWs = () => {if(!ws) return;ws.send(JSON.stringify({type:'message',data:{}}))
}const closeWs = () => {clearInterval(interval)ws.close()
}</script>
在本地直接运行浏览器即可!
如果有帮助,就点个赞再走 ^ ^