forked from unconed/TermKit
/
client.js
88 lines (73 loc) · 2.1 KB
/
client.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
(function ($) {
/**
* NodeKit client.
*/
var tc = termkit.client = function () {
var self = this;
// Prepare callback map.
this.handlers = {};
this.nextId = 1;
// Set up event handlers.
this.onConnect = function () {};
this.onDisconnect = function () {};
// Set up socket with back-end.
var s = this.socket = new io.Socket('localhost', { port: 2222 });
s.on('connect', function () {
// TODO: Handshake
self.onConnect();
});
s.on('disconnect', function() {
self.onDisconnect();
});
// Message processing loop.
s.on('message', function (data) {
self.receive(data);
});
// Open connection.
s.connect();
};
tc.prototype = {
// Invoke a method on the server.
invoke: function (method, args, returnCallback, handlers, sessionId) {
handlers = handlers || {};
handlers.Return = returnCallback;
var sequence = this.nextId++;
this.handlers[sequence] = handlers;
this.send(sessionId, sequence, method, args);
},
// Pass a message to the server.
send: function (sessionId, sequence, method, args) {
var json = JSON.stringify([ sessionId, sequence, method, args ]);
console.log('sending '+json);
this.socket.send(json);
},
// Receive a message from the server.
receive: function (data) {
// Parse incoming message.
var message = JSON.parse(data);
if (message && message.length) {
var sessionId = message[0],
sequence = message[1],
method = message[2],
args = message[3];
console.log('received '+data);
// Verify arguments.
if (typeof message[1] == 'number') {
// Locate handler for method and execute.
var handler = this.handlers[sequence];
if (handler) {
var prefix = method.split('.')[0];
if (prefix == 'return') {
handler.Return && handler.Return(args.data, args.code, args.status, sessionId);
// Clean-up callbacks.
delete this.handlers[sequence];
}
else {
handler[prefix] && handler[prefix](method, args);
}
}
}
}
},
};
})();