Solve the problem of using WebSocket?

WebSocket is used in vue project, WebSocket connection is defined in utils.js,

import base from "./api/base"

const ws = new WebSocket(`ws://${base.webSocket}/socket`);

export default ws

bring in files in main.js to bind to the instance prototype of vue;

import ws from "./request/webSocket" // api
Vue.prototype.ws = ws; // wsvue

then want to use WebSocket; directly through this.ws in all components
have the following questions:

  1. the state of ws.readyState is different when used in mounted of different pages, some are 0, some are 1,

    switch (ws.readyState) {
            case WebSocket.CONNECTING:
              console.log("CONNECTING")
              // do something
              break;
            case WebSocket.OPEN:
              console.log("OPEN")
              ws.send(this.userInfo.userId);
              // do something
              break;
            case WebSocket.CLOSING:
              console.log("CLOSING")
              // do something
              break;
            case WebSocket.CLOSED:
              console.log("CLOSED")
              // do something
              break;
            default:
              // this never happens
              break;
          }

    so there are some can not enter the open status, can not send messages, what should be done?

  2. using the callback of open, can"t the callback be triggered when the state changes?

    ws.addEventListener("open", function (event) {
            console.log("", data)
          });
  3. what is the idea of using WebSocket to receive background messages in real time on the page? Thank you

establishing a connection is an asynchronous process. Then component rendering is also an asynchronous process, so some components have not been connected after rendering ws, and some components have been connected after rendering ws. When mounted executes only once, the ws status is different. The callback of open does not know where you put it. If ws has been connected, then listening to open cannot be triggered.

Menu