-
Notifications
You must be signed in to change notification settings - Fork 0
/
promises-multi-address-example.js
67 lines (59 loc) · 1.91 KB
/
promises-multi-address-example.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
/*
* Cocker example, connect using a list of multiple hosts,
* through native Prmoises, using Cocker#prey and Cocker#die
*/
var log = console.log
, assert = require( 'assert' )
, net = require( 'net' )
, server = net.createServer()
, Cocker = require( '../' )
, trials = 4
, port = 63800
, opt = {
address : {
port : 0
}
, reconnection : {
trials : trials
, interval : 100
}
}
, attempts = 0
, ck = Cocker( opt )
, alist = []
, handle = ( sock ) => {
let addr = sock.address()
;
log( '- server: new socket connection', addr );
sock.on( 'close', ( args ) => log( '- server: socket closed', addr ) );
}
;
server.on( 'close', () => log( '- server: closed!' ) );
server.on( 'listening', () => log( '\n- server: listening on', server.address() ) );
server.on( 'connection', handle );
// server listen on the last resulting port
server.listen( port + trials );
for ( let i = 0; i < trials; ++i )
alist[ i ] = { host : '127.0.0.1', port : ++port }
;
// log Cocker events
ck.on( 'attempt', ( v, addr, lapse ) =>
log( '- cocker: (%d) attempt (%ds)', v, lapse / 1000, addr ) );
ck.on( 'offline', ( addr, haderr ) => log( '- cocker: offline!' ) );
ck.on( 'lost', ( v ) => log( '- cocker: lost!' ) );
log( '\n- execute prey on %d host(s):\n ', trials, alist );
ck.prey( alist )
// Promise resolved!
.then( ( args ) => log( '- cocker: connected!', args[ 0 ] ) )
// close connection
.then( () => {
log( '- cocker: close connection..' );
return ck.die();
} )
// socket closed
.then( ( args ) => log( '- cocker: socket closed', args[ 0 ] ) )
// all attempts are unsuccessful, Primose will be rejected
.catch( ( what ) => log( '-> rejected: \n-> error log:\n', what ) )
// finally close server
.then( () => server.close() )
;