websocket(一)封装使用

版权声明:非商业转载请附上地址与作者信息,谢谢! https://blog.csdn.net/jx950915/article/details/83088349

介绍

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

var WBT = function (obj) {
    /*
    websocket接口地址
    1、http请求还是https请求 前缀不一样
	2、ip地址host
    3、端口号
    */
    const config = obj ? obj : {}
    const protocol = (window.location.protocol == 'http:') ? 'ws://' : 'wss://';
    const host =  window.location.host;
    const port = ':8087';
    //接口地址url
    this.url = config.ip || protocol + host + port;
    //socket对象
    this.socket;
    //心跳状态  为false时不能执行操作 等待重连
    this.isHeartflag = false;
    //重连状态  避免不间断的重连操作
    this.isReconnect = false;
    //自定义Ws连接函数:服务器连接成功
    this.onopen = ((e) => {
        this.isHeartflag = true;
    	console.log(e)
    })
    //自定义Ws消息接收函数:服务器向前端推送消息时触发
    this.onmessage = ((e) => {
        //处理各种推送消息
// console.log(message)
        this.handleEvent(message)
    })
    //自定义Ws异常事件:Ws报错后触发
    this.onerror = ((e) => {
        console.log('error')
       this.isHeartflag = false;
        this.reConnect();
    })
    //自定义Ws关闭事件:Ws连接关闭后触发
    this.onclose = ((e) => {
        this.reConnect()
        console.log('close')
    })
    //初始化websocket连接
    this.initWs()
}

初始化 initWs

//初始化websocket连接 
WBT.prototype.initWs = function () {
	 window.WebSocket = window.WebSocket || window.MozWebSocket;
	 if (!window.WebSocket) { // 检测浏览器支持  			
	     console.error('错误: 浏览器不支持websocket');
	     return;
	 }
	 var that = this;
	 this.socket = new WebSocket(this.url); // 创建连接并注册响应函数  
	 this.socket.onopen = function (e) {
	     that.onopen(e);
	 };
	 this.socket.onmessage = function (e) {
	     that.onmessage(e);
	 };
	 this.socket.onclose = function (e) {
	     that.onclose(e);
	     that.socket = null; // 清理  		
	 };
	 this.socket.onerror = function (e) {
	     that.onerror(e);
	 }
	 return this;											
}

断线重连 reConnect

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

处理消息 handle

//处理消息
WBT.prototype.handleEvent = function (message) {
   	const action = message.action;
    const retCode = message.params.retCode.id;
    //根据action和retCode处理事件
    // console.log(action,retCode)
    if (this.handleAction[action][retCode]) this.handleAction[action][retCode]();
}
//事务处理 根据action
WBT.prototype.handleAction = {
     //登录反馈
   'loginRsp': {
    	'0': function () {
            console.log(0)
        },
        '3': function () {
            console.log(3)
        }
	}
}

发送消息-登录login

let defaultParam = {
    action: "loginReq",
    tsxId: "1",
    params:{}
}
WBT.prototype.login = function (params) {
    //ws还没建立连接(发生错误)
    if (!this.isHeartflag) {
    	console.log('连接中……')
      	return;
    }
    let loginParam = defaultParam;
    loginParam.params = params;
    //组装json数据
    this.socket.send(JSON.stringify(loginParam))
}

使用 index.html

var WS = new WBT()
var b = {
    dc: {
        id: "admin",
        passwd: "21232f297a57a5a743894a0e4a801fc3",
        version: "UDT-0.3.0"
    }
}
//发送消息
WS.login(b)

猜你喜欢

转载自blog.csdn.net/jx950915/article/details/83088349