WebSocket插件

;!(function(window){
    "use strict";    
    
    let Event = {
        wsMesEvent:function(message){
            console.log(message)
        }
    }
    
    ,dftOpt = {
        protocol:(window.location.protocol == 'http:') ? 'ws://' : 'wss://'
        ,host:window.location.host
        ,port:'80'
        ,path:''
        ,isReConect:false
        ,wsMesEvent:Event.wsMesEvent
    }
    
    ,Util = {
        arrayLike(arrayLike){ Array.from(arrayLike)}
        ,isArray(arr){Array.isArray(arr)}
        ,forEach(array,iterate){
            let index = -1
            ,length = array.length;
            if(typeof iterate != 'function'){return array;}
            while (++index < length) {
                iterate.call(array,array[index], index);
            }
        }
        ,isPlainObject(obj){
            let flag = false;
            if(!obj || typeof obj != 'object'){return flag;}
            if(obj.constructor.prototype.hasOwnProperty("isPrototypeOf")){
                flag = true;
            }
            return flag;
        }
        ,extend(...args){
            if(args.length <= 0){return};
            let target = args[0];
            if(args.length == 1){return args[0]};
            this.forEach(args,(arg,i) => {
                if(i!=0){
                    var keys = Object.keys(arg);
                    this.forEach(keys,(key,i) => {
                        var val = arg[key];
                        if(this.isPlainObject(val) || this.isArray(val)){
                            var newTarget = this.isArray(val)?[]:{};
                            target[key] = this.extend(newTarget,val);
                        }else{
                            target[key] = val;
                        }
                    });
                }
            });
            return target;
        }
    }

    ,Ws = function (opt) {
        //若是瀏覽器不支持websocket,直接退出
        if(!this.isSupportWs()){
            alert("對不起,您的瀏覽器在不支持WebSocket,請先升級您的瀏覽器!!");
            return;
        }
        
        let config = this.config = Util.extend({},dftOpt,opt);
        
        //接口地址url
        this.url = config.protocol + config.host +':'+config.port + config.path;
        //心跳狀態  爲false時不能執行操做 等待重連
        this.isHeartBeat = false ;
        //重連狀態  避免不間斷的重連操做
        this.isReconnect = config.isReConect;
        //發送的消息
        this.curSendMes = null;
        //響應的信息
        this.message = null;
        //建立webSocket
        this.ws;
        
        //初始化websocket
        this.initWs = function(){
            //建立WebSocket
            let ws = this.ws = new WebSocket(this.url);
            //Ws鏈接函數:服務器鏈接成功
            ws.onopen = (e) => {
                console.log(`與${this.config.host}:${this.config.port}${this.config.path}鏈接已創建...`)
                this.isHeartBeat = true;
                //發佈事件
                this.send();
            };
            //Ws消息接收函數:服務器向前端推送消息時觸發
            ws.onmessage = (e) => {
                //處理各類推送消
                this.message = e.data;
                config.wsMesEvent.apply(this,[e.data]);
            }
            //Ws異常事件:Ws報錯後觸發
            ws.onerror = (e) => {
               this.isHeartBeat = false;
               this.reConnect();
            }
            //Ws關閉事件:Ws鏈接關閉後觸發
            ws.onclose = (e) => {
                console.log('鏈接已關閉...');
                this.isHeartBeat = false;
                ws = null;
                this.reConnect();
            };
        };
        this.initWs();
    };
    
    //判斷是否支持WebSocket
    Ws.prototype.isSupportWs = function(){
        return (window.WebSocket || window.MozWebSocket)?true:false;
    }
    
    //從新鏈接
    Ws.prototype.reConnect = function () {
        //不須要從新鏈接,直接返回
        if(!this.isReconnect) return;
        this.isReconnect = true;
        //沒鏈接上 會一直重連,設置延遲避免請求過多
        setTimeout(()=>{
            this.initWs()
            this.isReconnect = false;
          }, 5000);
    }
    
    //發送消息
    Ws.prototype.send = function(content){
        this.curSendMes = content || this.curSendMes;
        if(this.isHeartBeat){
            this.ws.send(this.curSendMes);
        }
    }
    
    window.Ws = Ws;
    
})(window);

/***
 * 使用方式:
 * //創建鏈接
 * var ws1 = new Ws({
 *        host:'123.207.167.163'
 *        ,port:9010
 *        ,path:'/ajaxchattest'
 *        ,wsMesEvent:function(message){
 *            console.log(message)
 *        }
 *    });
 *    //發送請求
 *    ws1.send("111");
 *    
 *    //創建鏈接
 *    var ws2 = new Ws({
 *        host:'123.207.167.163'
 *        ,port:9010
 *        ,path:'/ajaxchattest'
 *        ,wsMesEvent:function(message){
 *            console.log(message)
 *        }
 *    });
 *    //發送請求
 *    ws2.send("222"); 
 * */
相關文章
相關標籤/搜索