vue中使用WebSocket

不用安装  直接将websocket.js文件放进utils文件夹中

let Socket = null
let setIntervalWesocketPush = null
// console.log(location.host, 'location.host');
// const wsNames = process.env.NODE_ENV == 'development' ? 'ws:' : 'wss:'
const socketUrl = process.env.NODE_ENV == 'development' ? 'ws://192.168.2.10:8092/ws' : 'wss://hjhome.link-bl.com/ws/' // socket连接地址
// const socketUrl = 'ws://192.168.2.10:8092/ws' // socket连接地址
// const socketUrl = 'wss://hjhome.link-bl.com/ws'
import store from '@/store'

// 0 :对应常量CONNECTING (numeric value 0),
// 正在建立连接连接,还没有完成。The connection has not yet been established.
// 1 :对应常量OPEN (numeric value 1),
// 连接成功建立,可以进行通信。The WebSocket connection is established and communication is possible.
// 2 :对应常量CLOSING (numeric value 2)
// 连接正在进行关闭握手,即将关闭。The connection is going through the closing handshake.
// 3 : 对应常量CLOSED (numeric value 3)
// 连接已经关闭或者根本没有建立。

/**
 * 建立websocket连接
 * @param {string} url ws地址
 */
export const createSocket = () => {
    Socket && Socket.close()
    console.log(socketUrl, 'socketUrl');
    if (!Socket) {
        Socket = new WebSocket(socketUrl)
        Socket.onopen = onopenWS
        Socket.onmessage = onmessageWS
        Socket.onerror = onerrorWS
        Socket.onclose = oncloseWS
    } else {
        console.log('websocket已连接')
    }
}

/**打开WS之后发送心跳 */
const onopenWS = () => {
    sendPing()
}

/**连接失败重连 */
const onerrorWS = () => {
    Socket.close()
    clearInterval(setIntervalWesocketPush)
    console.log('连接失败重连中')
    if (Socket.readyState !== 3) {
        Socket = null
        createSocket(socketUrl)
    }
}

/**WS数据接收统一处理 */
const onmessageWS = e => {
    // 将后端返回的数据存起来  渲染
    var items = JSON.parse(e.data);
    if (items.msg != 'ok') {
        store.dispatch("changeRes", items.data);
    }

    window.dispatchEvent(new CustomEvent('onmessageWS', {
        detail: {
            data: e.data
        }
    }))
}

/**
 * 发送数据但连接未建立时进行处理等待重发
 * @param {any} message 需要发送的数据
 */
const connecting = message => {
    setTimeout(() => {
        if (Socket.readyState === 0) {
            connecting(message)
        } else {
            Socket.send(JSON.stringify(message))
        }
    }, 1000)
}

/**
 * 发送数据
 * @param {any} message 需要发送的数据
 */
export const sendWSPush = message => {
    if (Socket !== null && Socket.readyState === 3) {
        Socket.close()
        createSocket(socketUrl)
    } else if (Socket.readyState === 1) {
        Socket.send(JSON.stringify(message))
    } else if (Socket.readyState === 0) {
        connecting(message)
    }
}


/**断开重连 */
const oncloseWS = () => {
    console.log('websocket已断开')
    Socket = null
    // clearInterval(setIntervalWesocketPush)
    // console.log('websocket已断开....正在尝试重连')
    // if (Socket.readyState !== 2) {
    //     Socket = null
    //     createSocket()
    // }

}

export const closeWs = () => {
    Socket.close()
}


/**发送心跳
 * @param {number} time 心跳间隔毫秒 默认5000
 * @param {string} ping 心跳名称 默认字符串ping
 */
export const sendPing = (time = 7000, ping = 'ping') => {
    clearInterval(setIntervalWesocketPush)
    Socket.send(JSON.stringify({
        "event": "heart"
    }))
    setIntervalWesocketPush = setInterval(() => {
        Socket.send(JSON.stringify({
            "event": "heart"
        }))
    }, time)
}

 在vue文件中使用

import { createSocket, sendWSPush, closeWs } from "@/utils/websocket.js";

data(){

    return{

      getsocketData: "",

    }

},

mounted() {

     this.wsConnect();

},

methods: {

    wsConnect() {

      createSocket();

      this.getsocketData = (e) => {

        // 创建接收消息函数

        let data = e && e.detail.data;

        if (data) {

          console.log(data,'后端返回的数据');

          let json = JSON.parse(data);

          if (json.event == "open") {

            // 已经建立了连接

            this.dialogVisible = true;

            let msg = { event: "open_screen" };

            // console.log(msg, "msgmsgmsg");

            sendWSPush(msg);

          }

        }

      };

      // 注册监听事件

      window.addEventListener("onmessageWS", this.getsocketData);

    },

    handleClose() {

      //想服务器发送断开连接的信息

      let msg = { event: "stop_screen" };

      sendWSPush(msg);

      closeWs();

      this.dialogVisible = false;

      window.removeEventListener("onmessageWS", this.getsocketData);

    },

    screenSharing() {

      this.wsConnect();

    },

},

你可能感兴趣的:(vue,vue.js,websocket,前端)