express 下搞一个 websocket 长连接

2023-12-14 11:16:19

?安装模块

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.remotePort
    clientObject[key] = {
        cli:client,
        heartBeat:1,
    }
    // 消息
    client.on('message', (message) => {
        client.send("收到你的消息了" + message)
    })
    // 关闭
    client.on('close', () => {
        var key = req.socket.remoteAddress + "_" +  req.socket.remotePort
        if(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].cli
        var heartBeat = clientObject[key].heartBeat
        clientObject[key].heartBeat += 1
        try {
            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模拟请求工具

再试试前端主动发消息的

文章来源:https://blog.csdn.net/myy2012/article/details/134987262
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。