安装模块
npm i express
npm i express-ws
新建文件app.js
先安排源码 监听端口 7777
var express = require('express')
var app = express()
require('express-ws')(app)var port = 7777
var clientObject = {}
app.ws('/', (client, req) => {// 连接var key = req.socket.remoteAddress + "_" + req.socket.remotePortclientObject[key] = {cli:client,heartBeat:1,}// 消息client.on('message', (message) => {client.send("收到你的消息了" + message)})// 关闭client.on('close', () => {var key = req.socket.remoteAddress + "_" + req.socket.remotePortif(clientObject[key]){delete clientObject[key]}});// 错误client.on('error', () => {});
})app.get('/', (req, res) => {res.send("hello 2023");
});
app.listen(port);// 心跳
setInterval (() => {var time = Date.now()for(var key in clientObject){var client = clientObject[key].clivar heartBeat = clientObject[key].heartBeatclientObject[key].heartBeat += 1try {var sData = {rspdata:{heartBeat:heartBeat,time:time,},}client.send(JSON.stringify(sData))} catch(e) {}}
}, 1000*3);
app.get('/', (req, res) => {
res.send("hello 2023");
});
测试下网页的显示
再搞个模块的客户端 测下心跳
Websocket在线测试-Websocket接口测试-Websocket模拟请求工具
再试试前端主动发消息的