;!(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");
 * */

最新文章

  1. Sql基础
  2. 干货!IT小伙伴们实用的网站及工具大集合!持续更新!
  3. MongoDB学习笔记~自己封装的Curd操作(查询集合对象属性,更新集合对象)
  4. jQuery基础知识准备
  5. js实现图片的大小自适应效果
  6. 实验十五_安装新的int 9中断例程
  7. json遍历key value
  8. ORACLE-用户常用数据字典的查询使用方法
  9. new jQuery.common
  10. 10招搞定web设计风格指南
  11. requests+正则表达式爬取ip
  12. C#Mvc批量删除
  13. ZOJ3967 : Card Game
  14. WIN7环境变量path误删(windows找不到文件‘%windir%\systempropertiesadvanced.exe’)的解决办法
  15. ipset可使iptables一次性封多个ip
  16. ie11 调试工具不能使用
  17. 读书笔记(03) - 性能 - JavaScript高级程序设计
  18. U盘安装win10操作系统
  19. DB2锁机制
  20. iOS 源代码混淆(初步混淆)

热门文章

  1. luogu P2210 Haywire
  2. Spring Boot 2.X(十):自定义注册 Servlet、Filter、Listener
  3. 学习笔记:flutter项目搭建(mac版)
  4. 聊聊缓存淘汰算法-LRU 实现原理
  5. angular7新特性
  6. 巨杉Tech | SequoiaDB数据域及存储规划
  7. Linux下部署Jenkins
  8. python模块的导入详解
  9. ESP8266 打造一款物联网产品---搭建环境编译及烧录
  10. mysql笔记一