-
Notifications
You must be signed in to change notification settings - Fork 0
/
promises-reconn-infinite-loop-example.js
101 lines (91 loc) · 2.76 KB
/
promises-reconn-infinite-loop-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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/*
* Cocker example, infinite hunt/watch loop
*/
var log = console.log
, floor = Math.floor
, random = Math.random
, now = Date.now
, assert = require( 'assert' )
, net = require( 'net' )
, server = net.createServer()
, Cocker = require( '../' )
, trials = 4
, port = 63800
, opt = {
address : {
port : port
}
, reconnection : {
trials : trials
, interval : 200
}
}
, attempts = 0
, ck = Cocker( opt )
, delay = ( t ) => new Promise ( ( solve ) => setTimeout( solve, t ) )
, destroy = ( socket, min, max ) => {
min = + min || 0;
max = + max || 4000;
let lapse = min + floor( random() * ( max - min + 1 ) )
;
delay( lapse ).then( ( lapse ) =>
log( '- server: destroy socket!' ) &
socket.destroy()
);
return lapse;
}
, sock = null
, handle = ( s ) => {
let saddr = s.address()
;
log( '- server: new connection from', saddr );
s.on( 'close', () => log( '- server: socket connection closed!', saddr ) );
// silly way to save socket reference
sock = s;
}
// flag to stop recursion
, stop = 0
// recursive loop
, loophunt = () =>
ck.hunt().then( stop || loopwatch, stop || loophunt )
, loopwatch = () =>
ck.watch().then( stop || loopwatch, stop || loophunt )
;
// log Cocker events
ck.on( 'attempt', ( t, addr, lapse ) =>
log( '- cocker: (%d) attempt (%ds)', t, lapse / 1000 ) );
ck.on( 'online', ( addr, haderr ) => log( '- cocker: online!' ) );
ck.on( 'offline', ( addr, haderr ) => log( '- cocker: offline!' ) );
ck.on( 'lost', ( v ) => log( '- cocker: lost!' ) );
ck.on( 'connect', ( v ) => log( '- cocker: connect!' ) );
ck.on( 'close', ( v ) => log( '- cocker: close!' ) );
// log server events
server.on( 'listening', ( v ) => log( '- server listening on:', server.address() ) );
server.on( 'close', () => log( '- server: close!' ) );
// handle socket connection
server.on( 'connection', handle );
// you can run the hunt loop before that the server is listening
var ploop = loophunt().catch( ( reason ) => log( '\n- error catched:\n', reason, '\n' ) )
// listen on wrong port
server.listen( 1 + port );
// simulate server multiple crash and reboot
delay( 4000 ).then( () =>
server.close() &
server.listen( port )
);
delay( 8000 ).then( () =>
destroy( sock ) &
server.close()
);
delay( 14000 ).then( () =>
server.listen( port )
// uncomment this line to stop looping (Promise rejection)
// & ( stop = true )
);
delay( 22000 ).then( () =>
destroy( sock ) &
server.close()
);
delay( 35000 ).then( () =>
server.listen( port )
);