1. 程式人生 > >vue-socket.io使用教程與踩坑記錄

vue-socket.io使用教程與踩坑記錄

全手打原創,轉載請標明出處:https://www.cnblogs.com/dreamsqin/p/12018866.html,多謝,=。=~
(如果對你有幫助的話請幫我點個贊啦)

請先允許我狠狠吐個槽:vue-socket.io相關中文部落格實在太少太少,來來去去就那麼幾篇,教程也比較零散,版本也比較老,就算我有暴風式搜尋還是找不到解決問題的方案,然後我怒了,開始看原始碼、寫測試demo、幾乎把相關的issues都看了一遍,折騰1天后終於。。。搞定了,下面總結一下~

前言

vue-socket.io其實是在socket.io-client基礎上做了一層封裝,將$socket掛載到vue例項上,同時你可以使用sockets物件

輕鬆實現元件化的事件監聽,讓你在vue專案中使用起來更方便。我目前用的vue-socket.io:3.0.7,可以在其package.json中看到它依賴於socket.io-client:2.1.1

我遇到的問題

websocket連線地址是從後端動態獲取,所以導致頁面載入時VueSocketIO例項還未建立,頁面中通過this.$socket.emit發起訂閱報錯,同時無法找到vue例項的sockets物件(寫在內部的事件將無法監聽到,就算後面已經連線成功)

如果你的websocket連線地址是靜態的(寫死的),可以只看使用教程,如果你跟我遇到了同樣的問題,那就跳躍到解決方案

console報錯如下:

使用教程

先拋開可能遇到的問題,按照官網的教程我們走一遍:

安裝

npm install vue-socket.io --save

引入(main.js)

import Vue from 'vue'
import store from './store'
import App from './App.vue'
import VueSocketIO from 'vue-socket.io'

Vue.use(new VueSocketIO({
    debug: true,
    connection: 'http://metinseylan.com:1992',
    vuex: {
        store,
        actionPrefix: 'SOCKET_',
        mutationPrefix: 'SOCKET_'
    },
    options: { path: "/my-app/" } //Optional options
}))

new Vue({
    router,
    store,
    render: h => h(App)
}).$mount('#app')
  • debug:生產環境建議關閉,開發環境可以開啟,這樣你就可以在控制檯看到socket連線和事件監聽的一些資訊,例如下面這樣:

  • connection:連線地址字首,注意!這裡只有字首,我之前被坑過,因為明明後端有給我返回上下文,但莫名其妙的被去除了,vue-socket.io這裡用到的是socket.io-clientManager api,關鍵原始碼如下(只看我寫中文備註的部分就好):

vue-socket.io(index.js)

import SocketIO from "socket.io-client";
export default class VueSocketIO {

    /**
     * lets take all resource
     * @param io
     * @param vuex
     * @param debug
     * @param options
     */
    constructor({connection, vuex, debug, options}){

        Logger.debug = debug;
        this.io = this.connect(connection, options); // 獲取到你設定的引數後就呼叫了connect方法
        this.useConnectionNamespace = (options && options.useConnectionNamespace);
        this.namespaceName = (options && options.namespaceName);
        this.emitter = new Emitter(vuex);
        this.listener = new Listener(this.io, this.emitter);
    }
    /**
   * registering SocketIO instance
   * @param connection
   * @param options
   */
  connect(connection, options) {
    if (connection && typeof connection === "object") {
      Logger.info(`Received socket.io-client instance`);
      return connection;
    } else if (typeof connection === "string") {
      const io = SocketIO(connection, options);// 其實用的是socket.io-client的Manager API
      Logger.info(`Received connection string`);
      return (this.io = io);
    } else {
      throw new Error("Unsupported connection type");
    }
  }

socket.io-client(index.js)

var url = require('./url');
function lookup (uri, opts) {
  if (typeof uri === 'object') {
    opts = uri;
    uri = undefined;
  }

  opts = opts || {};

  var parsed = url(uri); // 通過url.js對connection字首進行擷取
  var source = parsed.source;
  var id = parsed.id;
  var path = parsed.path;
  var sameNamespace = cache[id] && path in cache[id].nsps;
  var newConnection = opts.forceNew || opts['force new connection'] ||
                      false === opts.multiplex || sameNamespace;

  var io;

  if (newConnection) {
    debug('ignoring socket cache for %s', source);
    io = Manager(source, opts);
  } else {
    if (!cache[id]) {
      debug('new io instance for %s', source);
      cache[id] = Manager(source, opts);
    }
    io = cache[id];
  }
  if (parsed.query && !opts.query) {
    opts.query = parsed.query;
  }
  return io.socket(parsed.path, opts);// 實際呼叫的是解析後的字首地址
}
  • options.path: 這裡就可以填websocket連線地址的字尾,如果不填會被預設新增/socket.io,關鍵原始碼如下(只看我寫中文備註的部分就好):
    其他的options配置可以參見https://socket.io/docs/client-api/#Manager

socket.io-client(manager.js)

function Manager (uri, opts) {
  if (!(this instanceof Manager)) return new Manager(uri, opts);
  if (uri && ('object' === typeof uri)) {
    opts = uri;
    uri = undefined;
  }
  opts = opts || {};

  opts.path = opts.path || '/socket.io'; // 看到沒有,如果你不傳遞options.path引數的話會被預設安一個尾巴"/socket.io"
  this.nsps = {};
  this.subs = [];
  this.opts = opts;
  this.reconnection(opts.reconnection !== false);
  this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
  this.reconnectionDelay(opts.reconnectionDelay || 1000);
  this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
  this.randomizationFactor(opts.randomizationFactor || 0.5);
  this.backoff = new Backoff({
    min: this.reconnectionDelay(),
    max: this.reconnectionDelayMax(),
    jitter: this.randomizationFactor()
  });
  this.timeout(null == opts.timeout ? 20000 : opts.timeout);
  this.readyState = 'closed';
  this.uri = uri;
  this.connecting = [];
  this.lastPing = null;
  this.encoding = false;
  this.packetBuffer = [];
  var _parser = opts.parser || parser;
  this.encoder = new _parser.Encoder();
  this.decoder = new _parser.Decoder();
  this.autoConnect = opts.autoConnect !== false;
  if (this.autoConnect) this.open();
}
  • vuex: 配置後可以在store.jsmutations或者actions監聽到Vue-Socket.io事件(例如:connect、disconnect、reconnect等),這部分目前用得比較少,也挺簡單,如果有疑問可以給我留言我再單獨提供教程。

    使用(Page.vue)

    注意:熟悉socket.io-client的應該知道,預設情況下,websocket在建立例項的時候就會自動發起連線了,所以切記不要在元件中重複發起連線。如果你想自己控制發起連線的時機可以將options.autoConnect設定為false
export default {
    name: 'Page',
    sockets: {// 通過vue例項物件sockets實現元件中的事件監聽
      connect: function () {// socket的connect事件
        console.log('socket connected from Page')
      },
      STREAM_STATUS(data) {// 後端按主題名推送的訊息資料
          console.log('Page:' + data)
      }
    },
    mounted() {
      console.log('page mounted')
      this.$socket.emit('STREAM_STATUS', { subscribe: true })// 在頁面載入時發起訂閱,“STREAM_STATUS”是你跟後端約定好的主題名
    }
  }

事件除了在sockets物件中預設監聽,你還可以在外部單獨註冊事件監聽或取消註冊:

this.sockets.subscribe('EVENT_NAME', (data) => {
    this.msg = data.message;
});

this.sockets.unsubscribe('EVENT_NAME');

但這種方式從原始碼上看是不支援引數傳遞的,只支援傳遞事件名及回撥函式(部分原始碼如下):

vue-Socket.io(mixin.js)

beforeCreate(){
        if(!this.sockets) this.sockets = {};

        if (typeof this.$vueSocketIo === 'object') {
            for (const namespace of Object.keys(this.$vueSocketIo)) {
                this.sockets[namespace] = {
                    subscribe: (event, callback) => {
                        this.$vueSocketIo[namespace].emitter.addListener(event, callback, this);
                    },
                    unsubscribe: (event) => {
                        this.$vueSocketIo[namespace].emitter.removeListener(event, this);
                    }
                }
            }
        } else {
            this.$vueSocketIo.emitter.addListener(event, callback, this);
            this.$vueSocketIo.emitter.removeListener(event, this);
        }
    }

解決方案

針對我上面描述的問題,最大原因就在於獲取socket連線地址是非同步請求,如文章開頭的截圖,page mounted列印時,this.$socket還是undefined。所以我們要做的就是怎麼樣讓頁面載入在VueSocketIO例項建立之後。
我提供兩種解決方案,具體怎麼選擇看你們的需求~

保證拿到socket連線地址後再將vue例項掛載到app

缺點:如果你獲取socket地址的請求失敗了,整個專案的頁面都載入不出來(一般伺服器出現問題才會有這種情況產生)
優點:實現簡單,一小段程式碼挪個位置就好

main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ParentApi from '@/api/Parent'
import VueSocketIO from 'vue-socket.io'

/* 使用vue-socket.io */
ParentApi.getSocketUrl().then((res) => {
    Vue.use(new VueSocketIO({
        debug: false,
        connection: res.data.path,
        options: { path: '/my-project/socket.io' }
    }))
    new Vue({
        router,
        store,
        render: h => h(App)
    }).$mount('#app')
})

控制檯列印如下圖:


結合connect事件+store+路由守衛實現攔截

原理:非同步請求回撥中建立VueSocketIO例項並監聽connect事件,監聽回撥中修改isSuccessConnect引數的值,在Page頁面路由中增加beforeEnter守衛,利用setInterval週期性判斷isSuccessConnect的值,滿足條件則取消定時執行並路由跳轉。
缺點:實現起來稍微複雜一點
優點:不會影響其他頁面的載入

main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ParentApi from '@/api/Parent'
import VueSocketIO from 'vue-socket.io'

ParentApi.getSocketUrl().then((res) => {
  let vueSocketIo = new VueSocketIO({
    debug: false,
    connection: res.data.path,
    options: { path: '/my-project/socket.io' }
  })
  // 監聽connect事件,設定isSuccessConnect為true
  vueSocketIo.io.on('connect', () => {
    console.log('socket connect from main.js')
    store.commit('newIsSuccessConnect', true)
  })
  Vue.use(vueSocketIo)
})

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
store.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    // socket連線狀態
    isSuccessConnect: false
  },
  mutations: {
    newIsSuccessConnect(state, value) {
      state.isSuccessConnect = value
    }
  },
  getters: {
    getIsSuccessConnect: state => {
      return state.isSuccessConnect
    }
  },
  actions: {
  }
})
router.js
import Vue from 'vue'
import Router from 'vue-router'
import store from './store'

Vue.use(Router)

export default new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/page',
      name: 'Page',
      component: () => import(/* webpackChunkName: "Page" */ './pages/Page.vue'),
      beforeEnter: (to, from, next) => {
        let intervalId = setInterval(() => {
         // 直到store中isSuccessConnect為true時才能進入/page
          if (store.getters.getIsSuccessConnect) {
            clearInterval(intervalId)
            next()
          }
        }, 500)
      }
    }
  ]
})

控制檯列印如下圖:

參考資料:

1、vue-socket.io:https://github.com/MetinSeylan/Vue-Socket.io
2、socket.io-client:https://github.com/socketio/socket.io-client
3、vue-router守衛:https://router.vuejs.org/zh/guide/advanced/navigation-guards.html#%E8%B7%AF%E7%94%B1%E7%8B%AC%E4%BA%AB%E7%9A%84%E5%AE%88%E5%8D