wsNotify.js 945 Bytes
Newer Older
wanli's avatar
wanli committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
import Vue from "vue";
import defaultSettings from "@/settings";

let wsNotify = null;

const connectWSServer = () => {
  try {
    wsNotify = new WebSocket(
      "ws://" +
        window.location.hostname +
        ":" +
        defaultSettings.port +
        "/ws/api/v1/notify"
    );
  } catch (err) {
    console.error(err);
  }
};

connectWSServer();

window.wsNotify = wsNotify;

wsNotify.notifyBus = new Vue();

wsNotify.onopen = function(event) {
  console.log("wsNotify websocket is conneted!", event);
};

wsNotify.onmessage = function(event) {
  var message = JSON.parse(event.data);
  console.log(message);
  // console.log(message["type"]);
  wsNotify.notifyBus.$emit(message["type"], message);
};

wsNotify.onerror = function(event) {
  console.log(event);
};

wsNotify.onclose = function(event) {
  // 关闭 websocket
  console.log("wsNotify websocket is colosed!", event);
  // connectWSServer();
};

export default wsNotify;