forked from you21979/node-electrum-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit_socket.js
More file actions
56 lines (52 loc) · 1.27 KB
/
init_socket.js
File metadata and controls
56 lines (52 loc) · 1.27 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
'use strict'
const net = require('net');
const TIMEOUT = 10000
const getSocket = (protocol, options) => {
switch(protocol){
case 'tcp':
return new net.Socket();
case 'tls':
case 'ssl':
try {
const tls = require('tls');
} catch (e) {
throw new Error('tls package could not be loaded');
}
return new tls.TLSSocket(options);
}
throw new Error('unknown protocol')
}
const initSocket = (self, protocol, options) => {
const conn = getSocket(protocol, options);
conn.setTimeout(TIMEOUT)
conn.setEncoding('utf8')
conn.setKeepAlive(true, 0)
conn.setNoDelay(true)
conn.on('connect', () => {
conn.setTimeout(0)
self.onConnect()
})
conn.on('close', (e) => {
self.onClose(e)
})
conn.on('timeout', () => {
const e = new Error('ETIMEDOUT')
e.errorno = 'ETIMEDOUT'
e.code = 'ETIMEDOUT'
e.connect = false
conn.emit('error', e)
})
conn.on('data', (chunk) => {
conn.setTimeout(0)
self.onRecv(chunk)
})
conn.on('end', (e) => {
conn.setTimeout(0)
self.onEnd(e)
})
conn.on('error', (e) => {
self.onError(e)
})
return conn
}
module.exports = initSocket