-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.simpleclient.js
65 lines (61 loc) · 1.67 KB
/
lib.simpleclient.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
var wssClient = require('ws');
var _ = require('underscore');
function simpleclient(host, port, options) {
var scope = this;
this.host = host;
this.port = port;
this.options = _.extend({
onConnect: function() {},
onReceive: function() {},
onFail: function() {},
onClose: function() {}
}, options);
this.wss = new wssClient("ws://"+host+":"+port);
try {
this.wss.on('open', function() {
//scope.log("CONNECTED", "ws://"+host+":"+port);
scope.options.onConnect(scope);
});
this.wss.on('message', function(message) {
//scope.log("RECEIVING", scope.wsdecode(message));
scope.options.onReceive(scope, scope.wsdecode(message));
});
this.wss.on('close', function(code) {
//scope.log("CLOSED", code);
scope.options.onClose(scope, code);
});
this.wss.on('error', function(message) {
if (message.code == "ECONNREFUSED") {
scope.log("ERROR", "Connection Refused");
} else {
scope.log("ERROR", message, message.code);
}
scope.options.onFail(scope, message);
});
} catch(e) {
console.log("error :(",e);
}
}
simpleclient.prototype.send = function(data) {
this.wss.send(this.wsencode(data));
}
simpleclient.prototype.close = function() {
this.wss.close();
}
simpleclient.prototype.log = function(data, data2) {
var red, blue, reset;
red = '\u001b[31m';
blue = '\u001b[34m';
reset = '\u001b[0m';
console.log(red+"<CLIENT@"+this.host+":"+this.port+">");
for (i in arguments) {
console.log(reset, arguments[i],reset);
}
}
simpleclient.prototype.wsencode = function(data) {
return JSON.stringify(data);
}
simpleclient.prototype.wsdecode = function(data) {
return JSON.parse(data);
}
exports.simpleclient = simpleclient;