forked from aprock/react-native-tcp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TcpSocket.js
467 lines (382 loc) · 10.9 KB
/
TcpSocket.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
/**
* Copyright (c) 2015-present, Peel Technologies, Inc.
* All rights reserved.
*
* @providesModule TcpSocket
* @flow
*/
if (!(global.process && global.process.nextTick)) {
global.process = require('process'); // needed to make stream-browserify happy
}
var Buffer = (global.Buffer = global.Buffer || require('buffer').Buffer);
var util = require('util');
var stream = require('stream-browserify');
// var EventEmitter = require('events').EventEmitter;
var ipRegex = require('ip-regex');
var { NativeEventEmitter, NativeModules } = require('react-native');
var Sockets = NativeModules.TcpSockets;
var base64 = require('base64-js');
var Base64Str = require('./base64-str');
var noop = function () { };
var instances = 0;
var STATE = {
DISCONNECTED: 0,
CONNECTING: 1,
CONNECTED: 2,
};
function TcpSocket(options: ?{ id: ?number }) {
if (!(this instanceof TcpSocket)) {
return new TcpSocket(options);
}
if (options && options.id) {
// e.g. incoming server connections
this._id = Number(options.id);
if (this._id <= instances) {
throw new Error('Socket id ' + this._id + 'already in use');
}
} else {
// javascript generated sockets range from 1-1000
this._id = instances++;
}
this._eventEmitter = new NativeEventEmitter(Sockets);
stream.Duplex.call(this, {});
// ensure compatibility with node's EventEmitter
if (!this.on) {
this.on = this.addListener.bind(this);
}
// these will be set once there is a connection
this.writable = this.readable = false;
this._state = STATE.DISCONNECTED;
this.read(0);
}
util.inherits(TcpSocket, stream.Duplex);
TcpSocket.prototype._debug = function () {
if (__DEV__) {
var args = [].slice.call(arguments);
args.unshift('socket-' + this._id);
console.log.apply(console, args);
}
};
// TODO : determine how to properly overload this with flow
TcpSocket.prototype.connect = function (options, callback): TcpSocket {
this._registerEvents();
if (options === null || typeof options !== 'object') {
// Old API:
// connect(port, [host], [cb])
var args = this._normalizeConnectArgs(arguments);
return TcpSocket.prototype.connect.apply(this, args);
}
if (typeof callback === 'function') {
this.once('connect', callback);
}
var host = options.host || 'localhost';
var port = options.port || 0;
var localAddress = options.localAddress;
var localPort = options.localPort;
if (localAddress && !ipRegex({ exact: true }).test(localAddress)) {
throw new TypeError(
'"localAddress" option must be a valid IP: ' + localAddress,
);
}
if (localPort && typeof localPort !== 'number') {
throw new TypeError('"localPort" option should be a number: ' + localPort);
}
if (typeof port !== 'undefined') {
if (typeof port !== 'number' && typeof port !== 'string') {
throw new TypeError(
'"port" option should be a number or string: ' + port,
);
}
port = +port;
if (!isLegalPort(port)) {
throw new RangeError('"port" option should be >= 0 and < 65536: ' + port);
}
}
if (options.timeout) {
this.setTimeout(options.timeout);
} else if (this._timeout) {
this._activeTimer(this._timeout.msecs);
}
this._state = STATE.CONNECTING;
this._debug('connecting, host:', host, 'port:', port);
this._destroyed = false;
Sockets.connect(this._id, host, Number(port), options);
return this;
};
// Check that the port number is not NaN when coerced to a number,
// is an integer and that it falls within the legal range of port numbers.
function isLegalPort(port: number): boolean {
if (typeof port === 'string' && port.trim() === '') {
return false;
}
return +port === port >>> 0 && port >= 0 && port <= 0xffff;
}
TcpSocket.prototype.read = function (n) {
if (n === 0) {
return stream.Readable.prototype.read.call(this, n);
}
this.read = stream.Readable.prototype.read;
this._consuming = true;
return this.read(n);
};
// Just call handle.readStart until we have enough in the buffer
TcpSocket.prototype._read = function (n) {
this._debug('_read');
if (this._state === STATE.CONNECTING) {
this._debug('_read wait for connection');
this.once('connect', () => this._read(n));
} else if (!this._reading) {
// not already reading, start the flow
this._debug('Socket._read resume');
this._reading = true;
this.resume();
}
};
TcpSocket.prototype._activeTimer = function (msecs, wrapper) {
if (this._timeout && this._timeout.handle) {
clearTimeout(this._timeout.handle);
}
if (!wrapper) {
var self = this;
wrapper = function () {
self._timeout = null;
self.emit('timeout');
};
}
this._timeout = {
handle: setTimeout(wrapper, msecs),
wrapper: wrapper,
msecs: msecs,
};
};
TcpSocket.prototype._clearTimeout = function () {
if (this._timeout) {
clearTimeout(this._timeout.handle);
this._timeout = null;
}
};
TcpSocket.prototype.setTimeout = function (msecs: number, callback: () => void) {
if (msecs === 0) {
this._clearTimeout();
if (callback) {
this.removeListener('timeout', callback);
}
} else {
if (callback) {
this.once('timeout', callback);
}
this._activeTimer(msecs);
}
return this;
};
TcpSocket.prototype.address = function (): {
port: number,
address: string,
family: string,
} {
return this._address;
};
TcpSocket.prototype.end = function (data, encoding) {
stream.Duplex.prototype.end.call(this, data, encoding);
this.writable = false;
if (this._destroyed) {
return;
}
if (data) {
this.write(data, encoding);
}
if (this.readable) {
this.read(0);
this.readable = false;
}
this._destroyed = true;
this._debug('ending');
Sockets.end(this._id);
};
TcpSocket.prototype.destroy = function () {
if (!this._destroyed) {
this._destroyed = true;
this._debug('destroying');
this._clearTimeout();
Sockets.destroy(this._id);
}
};
TcpSocket.prototype._registerEvents = function (): void {
if (this._subs && this._subs.length > 0) {
return;
}
this._subs = [
this._eventEmitter.addListener('connect', ev => {
if (this._id !== ev.id) {
return;
}
this._onConnect(ev.address);
}),
this._eventEmitter.addListener('connection', ev => {
if (this._id !== ev.id) {
return;
}
this._onConnection(ev.info);
}),
this._eventEmitter.addListener('data', ev => {
if (this._id !== ev.id) {
return;
}
this._onData(ev.data);
}),
this._eventEmitter.addListener('close', ev => {
if (this._id !== ev.id) {
return;
}
this._onClose(ev.hadError);
}),
this._eventEmitter.addListener('error', ev => {
if (this._id !== ev.id) {
return;
}
this._onError(ev.error);
}),
];
};
TcpSocket.prototype._unregisterEvents = function (): void {
this._subs.forEach(e => e.remove());
this._subs = [];
};
TcpSocket.prototype._onConnect = function (address: {
port: number,
address: string,
family: string,
}): void {
this._debug('received', 'connect');
setConnected(this, address);
this.emit('connect');
this.read(0);
};
TcpSocket.prototype._onConnection = function (info: {
id: number,
address: { port: number, address: string, family: string },
}): void {
this._debug('received', 'connection');
var socket = new TcpSocket({ id: info.id });
socket._registerEvents();
setConnected(socket, info.address);
this.emit('connection', socket);
};
TcpSocket.prototype._onData = function (data: string): void {
this._debug('received', 'data');
if (this._timeout) {
this._activeTimer(this._timeout.msecs);
}
if (data && data.length > 0) {
// debug('got data');
// read success.
// In theory (and in practice) calling readStop right now
// will prevent this from being called again until _read() gets
// called again.
var ret = this.push(new Buffer(data, 'base64'));
if (this._reading && !ret) {
this._reading = false;
this.pause();
}
return;
}
};
TcpSocket.prototype._onClose = function (hadError: boolean): void {
this._debug('received', 'close');
setDisconnected(this, hadError);
};
TcpSocket.prototype._onError = function (error: string): void {
this._debug('received', 'error');
this.emit('error', normalizeError(error));
this.destroy();
};
TcpSocket.prototype.write = function (chunk, encoding, cb) {
if (typeof chunk !== 'string' && !Buffer.isBuffer(chunk)) {
throw new TypeError(
'Invalid data, chunk must be a string or buffer, not ' + typeof chunk,
);
}
return stream.Duplex.prototype.write.apply(this, arguments);
};
TcpSocket.prototype._write = function (
buffer: any,
encoding: ?String,
callback: ?(err: ?Error) => void,
): boolean {
var self = this;
if (this._state === STATE.DISCONNECTED) {
throw new Error('Socket is not connected.');
} else if (this._state === STATE.CONNECTING) {
// we're ok, GCDAsyncSocket handles queueing internally
}
callback = callback || noop;
var str;
if (typeof buffer === 'string') {
self._debug('socket.WRITE(): encoding as base64');
str = Base64Str.encode(buffer);
} else if (Buffer.isBuffer(buffer)) {
str = buffer.toString('base64');
} else {
throw new TypeError(
'Invalid data, chunk must be a string or buffer, not ' + typeof buffer,
);
}
Sockets.write(this._id, str, function (err) {
if (self._timeout) {
self._activeTimer(self._timeout.msecs);
}
err = normalizeError(err);
if (err) {
self._debug('write failed', err);
return callback(err);
}
callback();
});
return true;
};
function setConnected(
socket: TcpSocket,
address: { port: number, address: string, family: string },
) {
socket.writable = socket.readable = true;
socket._state = STATE.CONNECTED;
socket._address = address;
}
function setDisconnected(socket: TcpSocket, hadError: boolean): void {
if (socket._state === STATE.DISCONNECTED) {
return;
}
socket._unregisterEvents();
socket._state = STATE.DISCONNECTED;
socket.emit('close', hadError);
}
function normalizeError(err) {
if (err) {
if (typeof err === 'string') {
err = new Error(err);
}
return err;
}
}
// Returns an array [options] or [options, cb]
// It is the same as the argument of Socket.prototype.connect().
TcpSocket.prototype._normalizeConnectArgs = function (args) {
var options = {};
if (args[0] !== null && typeof args[0] === 'object') {
// connect(options, [cb])
options = args[0];
} else {
// connect(port, [host], [cb])
options.port = args[0];
if (typeof args[1] === 'string') {
options.host = args[1];
}
}
var cb = args[args.length - 1];
return typeof cb === 'function' ? [options, cb] : [options];
};
// unimplemented net.Socket apis
TcpSocket.prototype.ref = TcpSocket.prototype.unref = TcpSocket.prototype.setNoDelay = TcpSocket.prototype.setKeepAlive = TcpSocket.prototype.setEncoding = function () {
/* nop */
};
module.exports = TcpSocket;