forked from JustinTulloss/zeromq.node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
req_rep.js
57 lines (42 loc) · 1.23 KB
/
req_rep.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
/*
*
* One requester two responders (round robin)
*
*/
var cluster = require('cluster'),
zeromq = require('zmq'),
port = 'tcp://127.0.0.1:12345';
if (cluster.isMaster) {
//Fork servers.
for (var i = 0; i < 2; i++) {
cluster.fork();
}
cluster.on('death', function(worker) {
console.log('worker ' + worker.pid + ' died');
});
//requester = client
var socket = zeromq.socket('req');
socket.identity = 'client' + process.pid;
socket.bind(port, function(err) {
if (err) throw err;
console.log('bound!');
setInterval(function() {
var value = Math.floor(Math.random()*100);
console.log(socket.identity + ': asking ' + value);
socket.send(value);
}, 100);
socket.on('message', function(data) {
console.log(socket.identity + ': answer data ' + data);
});
});
} else {
//responder = server
var socket = zeromq.socket('rep');
socket.identity = 'server' + process.pid;
socket.connect(port);
console.log('connected!');
socket.on('message', function(data) {
console.log(socket.identity + ': received ' + data.toString());
socket.send(data * 2);
});
}