Start webSocket Posted on 2016-07-08 | 现在系统采用的是comet长链接,要修改为websocket实现通信123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108/** * 代替comet * 相关点:feed,newnotice,remind,at,announcement,notice,privatemsg */define(function (require, exports, module) { 'use strict'; var regId = 1, handlerPoll = [];//注册事件的部分还可以用,要不要改名字啊? $.registLongPulling = function(fn) { var $body = $('body:first'); if (!$body.data(':data(rk-websocket)')) { $body.websocket({ message: function(evt, msg) { if (msg != 'timeout') { if(msg && (typeof msg !== 'Object')){ msg = $.parseJSON(msg); } try { for (var i = 0; i < handlerPoll.length; i++) { handlerPoll[i].call(msg, msg); } } catch (ex) { window.console && console.log('the callback of long pulling error: ' + String(handlerPoll[i])); } } } }); } if ($.isFunction(fn)) { fn.rid = regId; regId += 1; handlerPoll.push(fn); return fn.rid; } return 0; }; $.unregistLongPulling = function(fn) { if ($.isFunction(fn) && fn.rid) { for (var i = handlerPoll.length - 1; i > -1; i--) { if (handlerPoll[i].rid == fn.rid) { handlerPoll.splice(i, 1); } } } }; $.widget('rk.websocket', { options: { clientID: SESSION.cometClientId, userID: SESSION.user.id, message: $.noop, url:'wss://192.168.0.103:8989/ws?'//getHostName }, _create: function(){ var me = this; me._delay(function() { me.init(); }, 10 * 1000); }, init:function(){ var me = this, opt = me.options; var url = [opt.url,'clientId=', opt.clientID, '&alias=', opt.userID].join(''); var browserWebSocket = window.WebSocket || window.MozWebSocket; var webSocket = browserWebSocket; if (webSocket && !me.connection) { try { me.connection = new WebSocket(url); me._bind(); } catch (e) { console.error('没有websocket怎么办') } } }, _bind:function(){ var me = this; var connection = me.connection; if(connection){ connection.onopen = function() { me.onOpen() }; connection.onclose = function() { me.onClose() }; connection.onmessage = function(ev) { console.log(ev) me._trigger('message', null, ev.data); }; connection.onerror = function(e) { me.onError("websocket error", e) } } }, onOpen:function(){ console.info('websocket open'); }, onError:function(msg,e){ console.info(msg); }, onClose:function(){ console.info('websocket closed'); //this._destroy(); }, getHostName:function(){} });}); 戳这里->comet实现的流程图改成websocket以后的流程图 就是这么懒,可怎么整 参考文章 socket.io源码使用 HTML5 WebSocket 构建实时 Web 应用MDN - WebSocket