nodejs后端代码 server.js
//需要安装ws模块 npm install ws
const WebSocket = require("ws")
const port = 8085
const 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>
在本地直接运行浏览器即可!
如果有帮助,就点个赞再走 ^ ^文章来源:https://www.toymoban.com/news/detail-640329.html
文章来源地址https://www.toymoban.com/news/detail-640329.html
到了这里,关于nodejs实现前后端websocket通信+心跳示例的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!