美文网首页
Vue 实现SocketIo与webSocket

Vue 实现SocketIo与webSocket

作者: 前端小飞象 | 来源:发表于2021-03-17 15:45 被阅读0次

SpringBoot + Netty-SocketIO + Vue

后端实现参考文档:https://www.jianshu.com/p/c67853e729e2

注意: 前端在vue项目中不能使用 vue-socket.io,要使用 socket.io-client

vue-socket.io使用后,后端获取不到数据,会报null异常


  • 安装
npm install socket.io-client@2.3.0
  • 引入(在需要组件中或main中引用)
import Socketio from "socket.io-client";
  • 使用
//`${process.env.VUE_APP_SOCKET_URL}` 为http:localhost:8000,需要使用字符串形式
 this.socketIoClient = Socketio.connect(`${process.env.VUE_APP_SOCKET_URL}`, { query: 'orderId=' + this.orderInfo.orderId })
      //监听与服务器的连接状态
  this.socketIoClient.on("connect", function () {
    console.log("连接了服务器")
  })
  const _this = this
   //****为与后端协商的方法名称,
  this.socketIoClient.on('****', function (response) {
    //获取后端推送的数据
    //内部使用_this
  })

如果使用代理,直接Socketio.connect('/',{})用斜杠,代理注意需要配置/socket.io

      '/socket.io': {
        target: 'http://xx.0.0.xxx:9099/socket.io',
        changeOrigin: true,
        ws: true,
        pathRewrite: {
          '^/socket.io': '/'
        }
      }

vue中 vue-socket.io 的使用

  • 安装
npm install vue-socket.io
  • 引入(main中引用)

固定url

import VueSocketIO from 'vue-socket.io'
//写死url
Vue.use(new VueSocketIO({
  debug: true,
  connection: '/socket',//此处可以使用代理地址,/socket为 http:localhost:8000
}))

动态url(顺序很重要,要先new VueSocketIO,在import App)

import VueSocketIO from 'vue-socket.io'
import {getCode} from '@/api/api'
import Vue from 'vue'
getCode().then(res=>{
  Vue.use(new VueSocketIO({
    debug: true,
    connection: res.url,
  }))
})

import App from './App'
  • 使用
 //因为通过路由进当前页面sockets里的connect未被触发所以需在mounted里触发一次 
mounted(){
this.$socket.emit('connect', 1)
},
methods:{
 
},
sockets:{
  connect(){
    console.log('connect连接')
   // this.$socket.emit('commitVal', {})
   //推送消息给后端,commitVal是后端定义的
  },
  //reconnect重连
  reconnect(){
    this.$socket.emit('connect',1)
  },
  //getVal名字自定义 与服务端保持一致
  getVal(val){
    console.log(val)
  }

}

vue中 websocket 的使用

  • 安装
npm install sockjs-client
npm install stompjs
  • 引入(在需要组件中或main中引用)
import SockJS from "sockjs-client";
import Stomp from "stompjs";
  • 使用
//连接方法
  connection() {
        // 建立连接对象
        this.wsocket = new SockJS("/ecspay/pay/ws");
        // 获取STOMP子协议的客户端对象
        this.stompClient = Stomp.over(this.wsocket);
        // 向服务器发起websocket连接
        this.stompClient.connect(
            {},
            () => {
                this.stompClient.subscribe(
                    "/topic/payOrder/" + this.orderInfo.orderId,
                    (response) => {
                        // 订阅服务端提供的某个topic      
            },
            (err) => {
                // 连接发生错误时的处理函数
                console.log("失败");
                console.log(err);
            }
        );
    },
    //初始化并监听
    initWebSocket () {
      this.connection();
      let that = this;
      // 断开重连机制,尝试发送消息,捕获异常发生时重连
      this.timer = setInterval(() => {
        if (this.wsocket.readyState == 3) {
          console.log("断线了");
          that.connection();
        }
        if (this.wsocket.readyState == 1) {
          that.stompClient.send("ping");
        }
      }, 30000);
    },

相关文章

网友评论

      本文标题:Vue 实现SocketIo与webSocket

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