forked from BlueWallet/BlueWallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnet.js
110 lines (94 loc) · 2.68 KB
/
net.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
102
103
104
105
106
107
108
109
110
/**
* @fileOverview adapter for ReactNative TCP module
* This module mimics the nodejs net api and is intended to work in RN environment.
* @see https://github.com/Rapsssito/react-native-tcp-socket
*/
import TcpSocket from 'react-native-tcp-socket';
/**
* Constructor function. Resulting object has to act as it was a real socket (basically
* conform to nodejs/net api)
*
* @constructor
*/
function Socket() {
this._socket = false; // reference to socket thats gona be created later
// defaults:
this._noDelay = true;
this._listeners = {};
// functions not supported by RN module, yet:
this.setTimeout = () => {};
this.setEncoding = () => {};
this.setKeepAlive = () => {};
// proxying call to real socket object:
this.setNoDelay = noDelay => {
if (this._socket) this._socket.setNoDelay(noDelay);
this._noDelay = noDelay;
};
this.connect = (port, host, callback) => {
this._socket = TcpSocket.createConnection(
{
port,
host,
tls: false,
},
callback,
);
this._socket.on('data', data => {
this._passOnEvent('data', data);
});
this._socket.on('error', data => {
this._passOnEvent('error', data);
});
this._socket.on('close', data => {
this._passOnEvent('close', data);
});
this._socket.on('connect', data => {
this._passOnEvent('connect', data);
this._socket.setNoDelay(this._noDelay);
});
this._socket.on('connection', data => {
this._passOnEvent('connection', data);
});
};
this._passOnEvent = (event, data) => {
this._listeners[event] = this._listeners[event] || [];
for (const savedListener of this._listeners[event]) {
savedListener(data);
}
};
this.on = (event, listener) => {
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
};
this.removeListener = (event, listener) => {
this._listeners[event] = this._listeners[event] || [];
const newListeners = [];
let found = false;
for (const savedListener of this._listeners[event]) {
if (savedListener === listener) {
// found our listener
found = true;
// we just skip it
} else {
// other listeners should go back to original array
newListeners.push(savedListener);
}
}
if (found) {
this._listeners[event] = newListeners;
} else {
// something went wrong, lets just cleanup all listeners
this._listeners[event] = [];
}
};
this.end = () => {
this._socket.end();
};
this.destroy = () => {
this._socket.destroy();
};
this.write = data => {
this._socket.write(data);
};
}
module.exports.Socket = Socket;