forked from misablaha/node-jsonrpc2
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserver.js
More file actions
66 lines (55 loc) · 1.58 KB
/
server.js
File metadata and controls
66 lines (55 loc) · 1.58 KB
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
var rpc = require('../src/jsonrpc');
var server = rpc.Server.$create({
websocket: true
});
server.on('error', function (err){
console.log(err);
});
/* Expose two simple functions */
server.expose('add', function (args, opts, callback){
callback(null, args[0] + args[1]);
}
);
server.expose('multiply', function (args, opts, callback){
callback(null, args[0] * args[1]);
}
);
/* We can expose entire modules easily */
server.exposeModule('math', {
power: function (args, opts, callback){
callback(null, Math.pow(args[0], args[1]));
},
sqrt : function (args, opts, callback){
callback(null, Math.sqrt(args[0]));
}
});
/* By using a callback, we can delay our response indefinitely, leaving the
request hanging until the callback emits success. */
server.exposeModule('delayed', {
echo: function (args, opts, callback){
var data = args[0];
var delay = args[1];
setTimeout(function (){
callback(null, data);
}, delay);
},
add: function (args, opts, callback){
var first = args[0];
var second = args[1];
var delay = args[2];
setTimeout(function (){
callback(null, first + second);
}, delay);
}
}
);
// or server.enableAuth('myuser', 'secret123');
server.enableAuth(function(user, password){
return user === 'myuser' && password === 'secret123';
});
/* HTTP/Websocket server on port 8088 */
server.listen(8088, 'localhost');
/* Raw socket server on port 8089 */
server.listenRaw(8089, 'localhost');
/* can handle everything in one port using */
// server.listenHybrid(8888, 'localhost');