-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
69 lines (57 loc) · 1.26 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
/**
* Module dependencies
*/
var Server = require('./lib/server')
, Client = require('./lib/client')
, Command = require('./lib/command')
/**
* Expose `Command'
*/
exports.Command = Command;
/**
* Creates a command server
*
* @api public
* @param {Function} handle
*/
exports.createCommandServer = createCommandServer;
function createCommandServer (handle) {
var server = Server();
var send = server.socket.send;
server.socket.send = function (buffer) {
if (buffer instanceof Error) {
buffer = "error: "+buffer.message;
}
send.call(this, buffer);
};
server.socket.on('message', function (buf) {
var cmd = Command.decode(buf);
if (null == cmd) {
server.emit(
'error',
new TypeError("Unknown command encoding for `"+ String(buf) +"'")
);
} else {
if ('function' == typeof handle) {
handle(cmd);
}
server.emit(cmd.realm, cmd);
}
});
return server;
}
/**
* Creates a command client
*
* @api public
*/
exports.createCommandClient = createCommandClient;
function createCommandClient () {
var client = Client();
var send = client.send.bind(client);
client.send = function (cmd, fn) {
send(Command.encode(cmd), fn);
return this;
};
return client;
}