-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.js
108 lines (86 loc) · 2.41 KB
/
app.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
98
99
100
101
102
103
104
105
106
107
108
var net = require('net');
var Events = require("events").EventEmitter;
var TIME_OUT = 60 * 1000 * 10;
/**
* @param setting
* @constructor
*/
function OpenApiClient(options, callback) {
options || (options = {});
callback || (callback = function() {});
var self = this;
if (!options.appkey) {
throw "appkey is required ";
}
this._events = new Events();
self._client = net.connect({
port: options.port || 9500,
host: options.host || "127.0.0.1"
}, function(err) {
if (err) {
callback(err);
}
self._client.write(JSON.stringify({
type: "auth",
appkey: options.appkey || ""
}));
});
this._timeoutId = setInterval(function() {
if (!self._closeflag) {
if (new Date - self._timeout > TIME_OUT) {
self._events.emit("timeout");
self.close();
return;
}
self._client.write(JSON.stringify({
type: "keepalive"
}))
}
}, 1000 * 60 * 5);
this._timeout = new Date - 0;
self._client.on("data", function(data) {
var json = {},
dataStr = "";
try {
dataStr = data.toString();
json = JSON.parse(dataStr);
} catch (e) {
callback(e);
return;
}
switch (json.type) {
case "auth":
if (json.err < 0) {
callback(json);
} else {
callback();
}
break;
case "keepalive":
self._timeout = new Date - 0;
default:
self._events.emit("data", dataStr);
break;
}
});
self._client.on("close", function() {
clearInterval(self._timeoutId);
self._events.emit("close");
});
}
OpenApiClient.prototype = {
on: function() {
this._events.addListener.apply(this._events, arguments);
},
off: function() {
this._events.removeListener.apply(this._events, arguments);
},
close: function() {
// destroy 异步触发close 时间, 存在可能 interval 先运行,造成 write 时候出错
this._closeflag = true;
this._client.destroy();
}
}
module.exports = function(options, callback) {
return new OpenApiClient(options, callback);
}