forked from bcoin-org/bcoin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcp.js
94 lines (75 loc) · 1.75 KB
/
tcp.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
/*!
* tcp.js - tcp backend for bcoin
* Copyright (c) 2014-2017, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
var EventEmitter = require('events').EventEmitter;
var net = require('net');
var socks = require('./socks');
/**
* @exports net/tcp
*/
var tcp = exports;
/**
* Create a TCP socket and connect.
* @param {Number} port
* @param {String} host
* @param {String?} proxy
* @returns {Object}
*/
tcp.createSocket = function createSocket(port, host, proxy) {
if (proxy)
return socks.connect(proxy, port, host);
return net.connect(port, host);
};
/**
* Create a TCP server.
* @returns {Object}
*/
tcp.createServer = function createServer() {
var server = new net.Server();
var ee = new EventEmitter();
ee.listen = function listen(port, host) {
return new Promise(function(resolve, reject) {
server.listen(port, host, wrap(resolve, reject));
});
};
ee.close = function close() {
return new Promise(function(resolve, reject) {
server.close(wrap(resolve, reject));
});
};
ee.address = function address() {
return server.address();
};
ee.__defineGetter__('maxConnections', function() {
return server.maxConnections;
});
ee.__defineSetter__('maxConnections', function(value) {
server.maxConnections = value;
return server.maxConnections;
});
server.on('listening', function() {
ee.emit('listening');
});
server.on('connection', function(socket) {
ee.emit('connection', socket);
});
server.on('error', function(err) {
ee.emit('error', err);
});
return ee;
};
/*
* Helpers
*/
function wrap(resolve, reject) {
return function(err, result) {
if (err) {
reject(err);
return;
}
resolve(result);
};
}