-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconnect-timeout.js
More file actions
100 lines (83 loc) · 2.48 KB
/
connect-timeout.js
File metadata and controls
100 lines (83 loc) · 2.48 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
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
/* Network Socket Connect with Timeout */
/* jshint esversion: 6 */
/* jshint node: true */
"use strict";
const net = require('net');
module.exports = {
connect: connect
};
/* --- Utility Functions --- */
function isport(value) {
return Number.isInteger(value) && value >= 0 && value < 65536;
}
function destroy_socket(context) {
try {
context.socket.destroy();
} catch (unused) {}
}
/* --- Connect with Timeout --- */
function connect_timeout_next(context, callback) {
if (context.timeout !== null) {
context.timer = setTimeout(() => {
callback(new Error('Connect timed out'), null, true);
}, context.timeout);
}
context.socket.on('error', (err) => {
destroy_socket(context);
callback(err);
}).on('close', () => {
destroy_socket(context);
callback(new Error('Socket closed'));
}).on('timeout', () => {
destroy_socket(context);
callback(new Error('Socket timed out'));
});
context.socket.connect(context.endpoint.port, context.endpoint.host, (err) => {
if (err) {
callback(err);
} else if (!context.done) {
context.socket.removeAllListeners('error');
context.socket.removeAllListeners('close');
context.socket.removeAllListeners('timeout');
callback(null, context.socket);
}
});
}
/* --- Connect with Timeout Task --- */
function connect(options, callback) {
if (!options.endpoint) {
callback(new Error('Endpoint option required'));
return;
}
if (typeof options.endpoint.host !== 'string' ||
!isport(options.endpoint.port)) {
callback(new Error('Endpoint option is invalid'));
return;
}
if (options.timeout !== null &&
(!Number.isInteger(options.timeout) || options.timeout < 0)) {
callback(new Error('Timeout option is invalid'));
return;
}
const context = {
done: false,
endpoint: options.endpoint,
timeout: options.timeout,
timer: null,
socket: new net.Socket()
};
connect_timeout_next(context, (err, socket, timedout) => {
const endflag = !context.done;
context.done = true;
if (err) {
destroy_socket(context);
}
if (context.timer) {
clearTimeout(context.timer);
context.timer = null;
}
if (endflag) {
callback(err, socket, timedout);
}
});
}