DWQA QuestionsCategory: ProgramThe express WS onopen callback function does not execute
znw-test asked 1 month ago

The code is as follows

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 ("link closed");
    })
})

module.exports = router;

On (“message”) and on (“close”) can be called normally on the browser connection, that is, the onopen callback has not been executed. Why?To supplement the front-end code, use 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();
    }
  }, [])

,It’s all in the router,onopenThe event was triggered long ago(onconnectionThe same applies to events). This is equivalent to adding an event hook after the event is triggered.

1 Answers
Then go hiking answered 1 month ago

It’s all in the router,onopenThe event was triggered long ago(onconnectionThe same applies to events). This is equivalent to adding an event hook after the event is triggered.

znw-test replied 1 month ago

If I want to add a callback for the onopen event, where should I add it?

Then go hiking replied 1 month ago

The express WS library does not provide such events. You can only modify its source code. Roughly add:https://github.com/HenningM/e