websocket(一)封装使用

介绍

WebSocket用于在Web浏览器和服务器之间进行任意的双向数据传输的一种技术。WebSocket协议基于TCP协议实现,包含初始的握手过程,以及后续的多次数据帧双向传输过程。其目的是在WebSocket应用和WebSocket服务器进行频繁双向通信时,可以使服务器避免打开多个HTTP连接进行工作来节约资源,提高了工作效率和资源利用率。

API介绍

  1. 构造函数WebSocket(url, protocols):构造WebSocket对象,以及建立和服务器连接; protocols可选字段,代表选择的子协议
  2. 状态变量readyState: 代表当前连接的状态,短整型数据,取值为CONNECTING(值为0), OPEN(值为1), CLOSING(值为2), CLOSED(值为3)
  3. 方法变量close(code, reason): 关闭此WebSocket连接。
  4. 状态变量bufferedAmount: send函数调用后,被缓存并且未发送到网络上的数据长度
  5. 方法变量send(data): 将数据data通过此WebSocket发送到对端
  6. 回调函数onopen/onmessage/onerror/onclose: 当相应的事件发生时会触发此回调函数

代码

这里采用封装的思想 WBT

 1 var WBT = function (obj) {
 2     /*
 3     websocket接口地址
 4     1、http请求还是https请求 前缀不一样
 5     2、ip地址host
 6     3、端口号
 7     */
 8     const config = obj ? obj : {}
 9     const protocol = (window.location.protocol == 'http:') ? 'ws://' : 'wss://';
10     const host =  window.location.host;
11     const port = ':8087';
12     //接口地址url
13     this.url = config.ip || protocol + host + port;
14     //socket对象
15     this.socket;
16     //心跳状态  为false时不能执行操作 等待重连
17     this.isHeartflag = false;
18     //重连状态  避免不间断的重连操作
19     this.isReconnect = false;
20     //自定义Ws连接函数:服务器连接成功
21     this.onopen = ((e) => {
22         this.isHeartflag = true;
23         console.log(e)
24     })
25     //自定义Ws消息接收函数:服务器向前端推送消息时触发
26     this.onmessage = ((e) => {
27         //处理各种推送消息
28 // console.log(message)
29         this.handleEvent(message)
30     })
31     //自定义Ws异常事件:Ws报错后触发
32     this.onerror = ((e) => {
33         console.log('error')
34        this.isHeartflag = false;
35         this.reConnect();
36     })
37     //自定义Ws关闭事件:Ws连接关闭后触发
38     this.onclose = ((e) => {
39         this.reConnect()
40         console.log('close')
41     })
42     //初始化websocket连接
43     this.initWs()
44 }

初始化 initWs

 1 //初始化websocket连接 
 2 WBT.prototype.initWs = function () {
 3      window.WebSocket = window.WebSocket || window.MozWebSocket;
 4      if (!window.WebSocket) { // 检测浏览器支持              
 5          console.error('错误: 浏览器不支持websocket');
 6          return;
 7      }
 8      var that = this;
 9      this.socket = new WebSocket(this.url); // 创建连接并注册响应函数  
10      this.socket.onopen = function (e) {
11          that.onopen(e);
12      };
13      this.socket.onmessage = function (e) {
14          that.onmessage(e);
15      };
16      this.socket.onclose = function (e) {
17          that.onclose(e);
18          that.socket = null; // 清理          
19      };
20      this.socket.onerror = function (e) {
21          that.onerror(e);
22      }
23      return this;                                            
24 }

断线重连 reConnect

1 WBT.prototype.reConnect = function () {
2     if (this.isReconnect) return;
3     this.isReconnect = true;
4     //没连接上会一直重连,设置延迟避免请求过多
5     setTimeout(function () {
6         this.initWs()
7         this.isReconnect = false;
8        }, 2000);
9 }    

处理消息 handle

 1 //处理消息
 2 WBT.prototype.handleEvent = function (message) {
 3        const action = message.action;
 4     const retCode = message.params.retCode.id;
 5     //根据action和retCode处理事件
 6     // console.log(action,retCode)
 7     if (this.handleAction[action][retCode]) this.handleAction[action][retCode]();
 8 }
 9 //事务处理 根据action
10 WBT.prototype.handleAction = {
11      //登录反馈
12    'loginRsp': {
13         '0': function () {
14             console.log(0)
15         },
16         '3': function () {
17             console.log(3)
18         }
19     }
20 }

发送消息-登录login

 1 let defaultParam = {
 2     action: "loginReq",
 3     tsxId: "1",
 4     params:{}
 5 }
 6 WBT.prototype.login = function (params) {
 7     //ws还没建立连接(发生错误)
 8     if (!this.isHeartflag) {
 9         console.log('连接中……')
10           return;
11     }
12     let loginParam = defaultParam;
13     loginParam.params = params;
14     //组装json数据
15     this.socket.send(JSON.stringify(loginParam))
16 }

使用 index.html

 1 var WS = new WBT()
 2 var b = {
 3     dc: {
 4         id: "admin",
 5         passwd: "21232f297a57a5a743894a0e4a801fc3",
 6         version: "UDT-0.3.0"
 7     }
 8 }
 9 //发送消息
10 WS.login(b)

 

posted @ 2020-09-21 15:36  码上wonderful  阅读(1200)  评论(0编辑  收藏  举报