forked from ottomao/anyproxy-wsclient
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
97 lines (82 loc) · 2.09 KB
/
index.js
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
//Ref: https://github.com/alibaba/anyproxy/blob/master/web/lib/anyproxy_wsUtil.js
/*
web socket util for AnyProxy
https://github.com/alibaba/anyproxy
*/
/*
{
baseUrl : ""
}
config
config.baseUrl
config.port
config.onOpen
config.onClose
config.onError
config.onGetData
config.onGetUpdate
config.onGetBody
config.onError
*/
function anyproxy_wsUtil(config){
config = config || {};
if(!WebSocket){
throw (new Error("webSocket is not available on this browser"));
}
var self = this;
var baseUrl = config.baseUrl || "127.0.0.1",
socketPort = config.port || 8003;
var dataSocket = new WebSocket("ws://" baseUrl ":" socketPort);
self.bodyCbMap = {};
dataSocket.onmessage = function(event){
config.onGetData && config.onGetData.call(self,event.data);
try{
var data = JSON.parse(event.data),
type = data.type,
content = data.content,
reqRef = data.reqRef;
}catch(e){
config.onError && config.onError.call(self, new Error("failed to parse socket data - " e.toString()) );
}
if(type == "update"){
config.onGetUpdate && config.onGetUpdate.call(self, content);
}else if(type == "body"){
config.onGetBody && config.onGetBody.call(self, content, reqRef);
if(data.reqRef && self.bodyCbMap[reqRef]){
self.bodyCbMap[reqRef].call(self,content);
}
}
}
dataSocket.onopen = function(e){
config.onOpen && config.onOpen.call(self,e);
}
dataSocket.onclose = function(e){
config.onClose && config.onClose.call(self,e);
}
dataSocket.onerror = function(e){
config.onError && config.onError.call(self,e);
}
self.dataSocket = dataSocket;
};
anyproxy_wsUtil.prototype.send = function(data){
if(typeof data == "object"){
data = JSON.stringify(data);
}
this.dataSocket.send(data);
};
anyproxy_wsUtil.prototype.reqBody = function(id,callback){
if(!id) return;
var payload = {
type : "reqBody",
id : id
};
if(callback){
var reqRef = "r_" Math.random()*100 "_" (new Date().getTime());
payload.reqRef = reqRef;
this.bodyCbMap[reqRef] = callback;
}
this.send(payload);
};
if(typeof module != "undefined"){
module.exports = anyproxy_wsUtil;
}