• VUE项目开发中使用WebSocket



    初始化WebSocket
    initWebSocket(){ //初始化weosocket
    const wsuri = 'ws://10.100.45.8:8888/websocket';//ws地址
    this.websock = new WebSocket(wsuri);
    this.websock.onopen = this.websocketonopen;
    this.websock.onerror = this.websocketonerror;
    this.websock.onmessage = this.websocketonmessage;
    this.websock.onclose = this.websocketclose;
    // this.websock.addEventListener('open', function () { //监听
    // });

    },

    打开WebSocket
    websocketonopen(e) {
    let code = 4;
    this.websock.send(code);// 连接完成后向后端发送信息
    },

    遇到错误时执行
    websocketonerror(e) { //错误
    console.log("WebSocket连接发生错误");
    },

    接收后端返回的数据
    websocketonmessage(e){ //数据接收
    let data = JSON.parse(e.data);
    console.log(data)
    },

    关闭WebSocket,一般在页面关闭时关闭,VUE提供了destroyed方法可以再页面销毁时调用websocketclose。
    websocketclose(e){ //关闭
    this.websock.close();

    },

  • 相关阅读:
    16 Errors and Exceptions
    13 Asynchronous Programming
    wpf入门
    iframe cross domain
    ini_set("error_log",$error_path)设置
    MySQL中merge表存储引擎用法
    php中静态属性静态方法的用法
    PHP的SESSIONID生成原理
    composer的基本 使用
    相邻省份数组
  • 原文地址:https://www.cnblogs.com/luzt/p/11677595.html
Copyright © 2020-2023  润新知