DAY10 - websocket前端实作-以vue.js为例

今天我们就来讲一下,当我们专案中确定会导入websocket了,前端的工作流程会是怎样,要怎麽跟後端沟通又要怎麽实作呢?

STEP1. websocket规格文件

其实跟API一样,我们总要知道怎麽做跟後端沟通,才能进行。
文件里要包含的东西基本上也就包含几项资讯:

1. Websocket 连线资讯

前後端要开始启动websocket通道,就必须要知道要要怎麽连,连去哪。
因此我们会需要 websocket的URL,可能也会有要给的参数从其他资讯传入

URL ws://sample.com/infomation/{userId}/
Parameter(optional) userId: (从 http://sample.com/api/user API取得)

2. Websocket 发送资讯与通知讯息

什麽时候,後端会发送讯息给前端? 且前端得到的response是什麽呢?
这边的资讯就会包含: trigger这个websocket发送讯息的时机点、还有在这个时机点回应的格式。才能让前端知道,在怎样的时间点会收到怎样的资讯。

Trigger Point 当书本借阅状态改变的时候
Response 格式 { "action": "BookStatusChange", content: {"id": 001}}

STEP2. 前端实作websocket

这边分享一下自己在vue专案中建立的websocket作法

2-1. 利用vuex统一控管websockt传来的通知

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);
// 定义一个新的 Vue Store
const store = new Vuex.Store({
    state: {
        wsNotify: {},
    },
    mutations: {
        //当接收到最新的後端送来的websocket资讯,直接存到state中的wsNotify
        setWsNotify(state, param) {
            Vue.set(state, 'wsNotify', param);
        },
    }
    
})

2-2. 建立 ws.js 将所有websocket相关的事件流程统整 (在vue中我用mixin统整起来)

import { mapMutations } from 'vuex';
export const mixinWebsocket = {
    data(){
        return{
            ws: null,
        }
    },
    methods:{
         ...mapMutations(['setWsNotify']),
        //初始websocket
        initWebsocket(){
            let wsURL = `ws://sample.com/infomation/${userId}`;
            this.ws = new WebSocket(wsURL); //建立连线
            this.ws.onopen = this.websocketonopen;
            this.ws.error = this.websocketonerror;
            this.ws.onmessage = this.websocketonmessage;
            this.ws.onclose = this.websocketclose;
        },
        websocketonopen(){
            console.log('ws 连线成功~~');
        },
        websocketonerror(e){
            console.error('ws 连线失败',e);
        },
        websocketonmessage(e){
            // 後端通知前端,前端取得资料
            let _data = e.data;
            //当有後端资料送到前端,利用vuex存到共用的state
            this.setWsNotify({
                id:uuid.v4(), 
                data: JSON.parse(_data)
            });
            console.log('ws 取得资料',_data);
        },
        websocketsend(data){
            //前端丢资料
            console.log('send data',data);
        },
        websocketclose(){
            console.log('ws 关闭连线')
        }
    }
}

2-3. 选择连通websocket通道的时机 - 全站入口点

这边我自己曾经考虑过在某些特定的页面进入後再开启,但这样就会变成来回进入页面会开关通道频繁,因此我最後决定进到网站的时候,就将websocket通道开启,进到网站後,只进行一次handshake,就保持连线。
因此,在App.vue (全站入口),加入通道开启及关闭的方法。

import { mixinWebsocket } from '@/utils/ws';
export default {
    mixins: [mixinWebsocket],
    created(){
        this.initWebsocket(); //开啓前後端的websocket通道
    },
    destroy(){
        this.websocketclose(); //关闭websocket通道
    }
}

2-4. 在需要的页面watch vuex中state的WsNotify,从前端送资料或後端送资料给前端

import { mixinWebsocket } from '@/utils/ws';
export default {
    mixins: [mixinWebsocket],
    watch:{
        wsNotify:{
            handler(val){
                let {id, data} = val;
                // 根据data决定要do something
            },
            deep:true
        }
        
    },
    
}

以上大概是我的vue环境建立websocket流程,主要着重在後端通知前端,当然有些情况也是前端要告知後端。那就使用前面提到的websocketsend()传送资料就可以罗。
也很欢迎大家分享一下在vue.js中实作websocket的方法,也许有其他的写法更好,快来一起讨论吧~~


<<:  与不同阶段的使用者对话

>>:  Day 24 - fetch

[Android Studio 30天自我挑战] EditText的元件介绍

EditText与TextView相似,但EditText用於APP需要输入资料时,例如:输入姓名、...

Day#26 传送对话(1)

前言 前一天结束在点选某个搜寻到的使用者,今天接着做跟该使用者展开对话吧! New Conversa...

第27天 - 文件审核系统(5)_审核端1

今天开始来弄审核端的部分 如何判不同身分登入可参考第16天的文章 https://ithelp.it...

使用auto-sklearn demo AutoML

上一篇说明了Auto ML的基本概念, 本篇我们就来使用auto sklearn实作看看 Auto ...

Day20 - 使用 Hash 实作资料查询

GitHub 网址:https://github.com/ Heroku 网址:https://w...