赞
踩
源码:
- // 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;
- };
-
- }));
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。