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.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1bf5851-31f71.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1bf5851-31f71.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?