jQuery版本的websocket插件

  • 支持断线重连
  • 支持自动ping
  • 支持json自动转换

源码:

// AMD support
(function (factory) {
	"use strict";
	if (typeof define === 'function' && define.amd) {
		// using AMD; register as anon module
		define(['jquery'], factory);
	} else {
		// no AMD; invoke directly
		factory((typeof (jQuery) != 'undefined') ? jQuery : window.Zepto);
	}
}

(function ($) {
	"use strict";

	/*
		For example
		-----------
	
		var ws = $.websocket({
			url: 'ws://websocket/',
			message: function (data) {
				console.log(data);
			}
		});

		ws.send('test');
	*/

	$.websocket = function (options) {
		var defaults = {
			//各种参数、各种属性
			timeout: 15000, //ping的间隔时间
			ping: true, //是否ping
			debug: false, //是否调试状态
			reconnect: true, //是否自动重连
			open: function () { },
			close: function () { },
			error: function (e) { },
			message: function () { }
		};

		var tt;
		var pingObj;
		var lockReconnect = false;//避免重复连接
		var opt = $.extend(defaults, options);

		function init() {
			var ws;
			try {
				ws = new WebSocket(opt.url);
			} catch (ee) {
				ws = { send: function (m) { return false }, close: function () { } };
			}

			$(ws)
				.bind('open', open)
				.bind('close', function () {
					console.log('close');
					if (opt.reconnect) {
						retry(opt.url);
					}
					opt.close();
				})
				.bind('error', function (e) {
					console.log('error:' + JSON.stringify(e));
					if (opt.reconnect) {
						retry(opt.url);
					}
					opt.error(e);
				})
				.bind('message', message);

			ws.dosend = ws.send;
			ws.send = function (o) {
				if (opt.debug) {
					console.log('send:' + o);
				}
				this.dosend(o);
			}

			return ws;
		}

		var ws = init();

		function open() {
			if (opt.ping) {
				console.log('ping start');
				pingObj = setInterval(function () {
					try {
						console.log('ping');
						ws.send(0);
					} catch (e) {
						console.log('ping error', JSON.stringify(e));
						clearTimeout(pingObj);
						if (opt.reconnect) {
							retry();
						}
					}
				}, opt.timeout);
			}
			opt.open();
		}

		function message(e) {
			if (opt.debug) {
				console.log('message:' + e.originalEvent.data);
			}
			var o = e.originalEvent.data;
			if (typeof o == 'string') {
				try {
					var obj = JSON.parse(o);
					if (typeof obj == 'object' && obj) {
						opt.message(obj);
					} else {
						opt.message(o);
					}
				} catch (e) {
					opt.message(o);
				}
			} else {
				opt.message(o);
			}
		}

		function retry() {
			if (lockReconnect) {
				return;
			};
			lockReconnect = true;
			//没连接上会一直重连,设置延迟避免请求过多
			tt && clearTimeout(tt);
			if (opt.ping && pingObj != null) {
				clearTimeout(pingObj);
			}
			tt = setTimeout(function () {
				console.log('retry');
				ws = init();
				lockReconnect = false;
			}, 5000);
		}

		$(window).on('unload', (function () {
			console.log('unload');
			opt.reconnect = false;
			if (opt.ping && pingObj != null) {
				clearTimeout(pingObj);
			}
			ws.close();
			ws = null
		}));
		return ws;
	};

}));

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值