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:
-
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?
-
using the callback of open, can"t the callback be triggered when the state changes?
ws.addEventListener("open", function (event) { console.log("", data) });
- what is the idea of using WebSocket to receive background messages in real time on the page? Thank you