美文网首页
Vue使用vue-native-websocket连接webso

Vue使用vue-native-websocket连接webso

作者: itfitness | 来源:发表于2023-05-03 16:48 被阅读0次

安装

https://github.com/nathantsoi/vue-native-websocket

yarn add vue-native-websocket
# or
npm install vue-native-websocket --save

引入插件

import websocket from 'vue-native-websocket';
Vue.use(websocket, 'ws://localhost:8989', {// 需要连接的服务器地址,端打包后可以填地址(localhost:...),调试阶段需填写对应开发本地地址(同个局域网,能ping通的地址)或部署的在线服务地址
  reconnection: true, // (Boolean)是否自动重连,默认false
  reconnectionAttempts: 5, // 重连次数
  reconnectionDelay: 3000, // 再次重连等待时常(1000)
});

如果要手动连接的话使用如下代码

import websocket from 'vue-native-websocket';
//Websocket插件
Vue.use(websocket, '', {
  connectManually: true, // 手动连接
  format: 'json', // json格式
  reconnection: true, // 是否自动重连
  reconnectionAttempts: 5, // 自动重连次数
  reconnectionDelay: 2000, // 重连间隔时间
});
methods: {
    initWebSocket({
        this.$connect('ws://localhost:9090/alternative/connection/', { format: 'json' })
    },
}

监听回调

 methods: {
      // 初始化weosocket
      initWebSocket() {
       this.$socket.onopen = this.websocketonopen;//连接成功方法
       this.$socket.onerror = this.websocketonerror;//报错方法
       this.$socket.onmessage = this.websocketonmessage;// 接收端返回或推送信息的方法
       this.$socket.onclose = this.websocketclose;//关闭
      },
      // 链接ws服务器,e.target.readyState = 0/1/2/3   0 CONNECTING ,1 OPEN, 2 CLOSING, 3 CLOSED
      websocketonopen(e) {
        console.log('WebSocket连接成功', e);
      },
      // 接收端发送过来的信息,整个项目接收信息的唯一入口
      websocketonmessage(e) {
        
     },
     websocketonerror(e) {
        
     },
     websocketclose(e) {
        
     }
}

也可以这样

        mounted() {
            
        },
        sockets: {
            // 连接成功
            onopen() {
                console.log("socket success");
            },
            // 接收消息
            onmessage(e) {
                var res = JSON.parse(e.data)
            },
            // 连接报错
            onerror() {},
            // 关闭连接
            onclose() {
                console.log("socket close");
            },
        },
        methods: {}

发送消息

methods: {
    clickButton: function(val) {
        // $socket is [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) instance
        this.$socket.send('some data')
        // or with {format: 'json'} enabled
        this.$socket.sendObj({awesome: 'data'})
    }
  }

相关文章

网友评论

      本文标题:Vue使用vue-native-websocket连接webso

      本文链接:https://www.haomeiwen.com/subject/xcrtsdtx.html