Start webSocket

现在系统采用的是comet长链接,要修改为websocket实现通信

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/**
* 代替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以后的流程图

改成websocket以后的流程图

就是这么懒,可怎么整

参考文章

socket.io源码
使用 HTML5 WebSocket 构建实时 Web 应用
MDN - WebSocket