express-ws onopen回调函数不执行

代码如下

var express = require("express");
var expressWs = require("express-ws");
var router = express.Router();

expressWs(router);
var clientList = []
router.ws("/", function (ws, req) {
    ws.on("open", function (client) {
        clientList.push(client)
        console.log(clientList)
    })
    ws.on("message", function (msg) {
        console.log(msg);
        clientList.forEach(client=>{
            client.send(msg);
        })
    })
    ws.on("close", function () {
        console.log("链接关闭");
    })
})

module.exports = router;

浏览器连接上on("message")和on("close")都能正常调用,就是onOpen的回调没有被执行,这是为什么?

补充一下前端代码,是用的react + reconnecting-websocket

  const ws = useRef(null);
  useEffect(() => {
    if (Object.is(ws.current, null)) {
      ws.current = new ReconnectingWebSocket("ws://localhost:8080/ws")
      ws.current.onmessage = function (msg) {
        console.log(msg);
        let data = JSON.parse(msg.data);
        setMsgList({ type: 'add', data: data });
      }
      ws.current.onopen = function (e) {
        console.log(e);
      }
    }
    return () => {
      ws.current.close();
    }
  }, [])
阅读 3.7k
1 个回答

都已经进到 router 里了,onopen 事件早就触发完了(onconnection 事件同理)。你这相当于是事件触发完以后你才添加事件钩子。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题