@react-native-ohos/react-native-tcp-socket 6.3.1 → 6.4.0-bate.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/LICENSE +21 -21
  2. package/README.OpenSource +10 -10
  3. package/README.md +12 -12
  4. package/harmony/tcp_socket/BuildProfile.ets +17 -17
  5. package/harmony/tcp_socket/Index.ets +9 -6
  6. package/harmony/tcp_socket/build-profile.json5 +31 -31
  7. package/harmony/tcp_socket/hvigorfile.ts +6 -6
  8. package/harmony/tcp_socket/obfuscation-rules.txt +22 -22
  9. package/harmony/tcp_socket/oh-package.json5 +11 -11
  10. package/harmony/tcp_socket/src/main/cpp/CMakeLists.txt +8 -8
  11. package/harmony/tcp_socket/src/main/cpp/TcpSocketPackage.h +18 -18
  12. package/harmony/tcp_socket/src/main/cpp/generated/RNOH/generated/BaseReactNativeTcpSocketPackage.h +72 -72
  13. package/harmony/tcp_socket/src/main/cpp/generated/RNOH/generated/turbo_modules/TcpSocketModule.cpp +28 -28
  14. package/harmony/tcp_socket/src/main/cpp/generated/RNOH/generated/turbo_modules/TcpSocketModule.h +16 -16
  15. package/harmony/tcp_socket/src/main/cpp/generated/react/renderer/components/react_native_tcp_socket/ComponentDescriptors.h +24 -24
  16. package/harmony/tcp_socket/src/main/cpp/generated/react/renderer/components/react_native_tcp_socket/EventEmitters.cpp +16 -16
  17. package/harmony/tcp_socket/src/main/cpp/generated/react/renderer/components/react_native_tcp_socket/EventEmitters.h +17 -17
  18. package/harmony/tcp_socket/src/main/cpp/generated/react/renderer/components/react_native_tcp_socket/Props.cpp +19 -19
  19. package/harmony/tcp_socket/src/main/cpp/generated/react/renderer/components/react_native_tcp_socket/Props.h +18 -18
  20. package/harmony/tcp_socket/src/main/cpp/generated/react/renderer/components/react_native_tcp_socket/ShadowNodes.cpp +17 -17
  21. package/harmony/tcp_socket/src/main/cpp/generated/react/renderer/components/react_native_tcp_socket/ShadowNodes.h +23 -23
  22. package/harmony/tcp_socket/src/main/cpp/generated/react/renderer/components/react_native_tcp_socket/States.cpp +16 -16
  23. package/harmony/tcp_socket/src/main/cpp/generated/react/renderer/components/react_native_tcp_socket/States.h +18 -18
  24. package/harmony/tcp_socket/src/main/ets/Logger.ts +45 -45
  25. package/harmony/tcp_socket/src/main/ets/TcpEventListener.ts +120 -120
  26. package/harmony/tcp_socket/src/main/ets/TcpSocket.ts +16 -16
  27. package/harmony/tcp_socket/src/main/ets/TcpSocketClient.ts +443 -443
  28. package/harmony/tcp_socket/src/main/ets/{TcpSocketPackage.ts → TcpSocketPackage.ets} +27 -27
  29. package/harmony/tcp_socket/src/main/ets/TcpSocketServer.ts +150 -150
  30. package/harmony/tcp_socket/src/main/ets/TcpSocketTurboModule.ts +224 -224
  31. package/harmony/tcp_socket/src/main/ets/generated/components/ts.ts +5 -5
  32. package/harmony/tcp_socket/src/main/ets/generated/index.ets +5 -5
  33. package/harmony/tcp_socket/src/main/ets/generated/ts.ts +6 -6
  34. package/harmony/tcp_socket/src/main/ets/generated/turboModules/TcpSocketModule.ts +38 -38
  35. package/harmony/tcp_socket/src/main/ets/generated/turboModules/ts.ts +5 -5
  36. package/harmony/tcp_socket/src/main/module.json5 +11 -11
  37. package/harmony/tcp_socket/src/main/resources/base/element/string.json +8 -8
  38. package/harmony/tcp_socket/src/main/resources/en_US/element/string.json +8 -8
  39. package/harmony/tcp_socket/src/main/resources/zh_CN/element/string.json +8 -8
  40. package/harmony/tcp_socket/src/ohosTest/ets/test/Ability.test.ets +34 -34
  41. package/harmony/tcp_socket/src/ohosTest/ets/test/List.test.ets +4 -4
  42. package/harmony/tcp_socket/src/ohosTest/module.json5 +13 -13
  43. package/harmony/tcp_socket/src/test/List.test.ets +4 -4
  44. package/harmony/tcp_socket/src/test/LocalUnit.test.ets +32 -32
  45. package/harmony/tcp_socket/{ts.ts → ts.ets} +6 -6
  46. package/harmony/tcp_socket.har +0 -0
  47. package/lib/types/Globals.d.ts +2 -2
  48. package/lib/types/Server.d.ts +137 -137
  49. package/lib/types/Socket.d.ts +272 -272
  50. package/lib/types/TLSServer.d.ts +28 -28
  51. package/lib/types/TLSSocket.d.ts +50 -50
  52. package/lib/types/index.d.ts +80 -80
  53. package/package.json +83 -77
  54. package/src/Globals.js +12 -12
  55. package/src/Server.js +271 -271
  56. package/src/Socket.js +513 -513
  57. package/src/TLSServer.js +70 -70
  58. package/src/TLSSocket.js +93 -93
  59. package/src/TcpSocketModule.ts +39 -39
  60. package/src/index.js +144 -144
package/src/Socket.js CHANGED
@@ -1,513 +1,513 @@
1
- 'use strict';
2
-
3
- import EventEmitter from 'eventemitter3';
4
- import { Buffer } from 'buffer';
5
- import { TurboModuleRegistry, NativeModules } from 'react-native';
6
- import { nativeEventEmitter, getNextId } from './Globals';
7
-
8
- const Sockets = TurboModuleRegistry ? TurboModuleRegistry.get('TcpSocketModule') : NativeModules.TcpSockets;
9
-
10
-
11
- /**
12
- * @typedef {"ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "latin1" | "binary" | "hex"} BufferEncoding
13
- *
14
- * @typedef {import('react-native').NativeEventEmitter} NativeEventEmitter
15
- *
16
- * @typedef {{address: string, family: string, port: number}} AddressInfo
17
- *
18
- * @typedef {{localAddress: string, localPort: number, remoteAddress: string, remotePort: number, remoteFamily: string}} NativeConnectionInfo
19
- *
20
- * @typedef {{
21
- * port: number;
22
- * host?: string;
23
- * localAddress?: string,
24
- * localPort?: number,
25
- * interface?: 'wifi' | 'cellular' | 'ethernet',
26
- * reuseAddress?: boolean,
27
- * tls?: boolean,
28
- * tlsCheckValidity?: boolean,
29
- * tlsCert?: any,
30
- * }} ConnectionOptions
31
- *
32
- * @typedef {object} ReadableEvents
33
- * @property {() => void} pause
34
- * @property {() => void} resume
35
- *
36
- * @typedef {object} SocketEvents
37
- * @property {(had_error: boolean) => void} close
38
- * @property {() => void} connect
39
- * @property {(data: Buffer | string) => void} data
40
- * @property {() => void} drain
41
- * @property {(err: Error) => void} error
42
- * @property {() => void} timeout
43
- * @property {() => void} secureConnect
44
- *
45
- * @extends {EventEmitter<SocketEvents & ReadableEvents, any>}
46
- */
47
- export default class Socket extends EventEmitter {
48
- /**
49
- * Creates a new socket object.
50
- */
51
- constructor() {
52
- super();
53
- /** @package */
54
- this._id = getNextId();
55
- /** @private */
56
- this._eventEmitter = nativeEventEmitter;
57
- /** @type {EventEmitter<'written', any>} @private */
58
- this._msgEvtEmitter = new EventEmitter();
59
- /** @type {number} @private */
60
- this._timeoutMsecs = 0;
61
- /** @type {number | undefined} @private */
62
- this._timeout = undefined;
63
- /** @private */
64
- this._encoding = undefined;
65
- /** @private */
66
- this._msgId = 0;
67
- /** @private */
68
- this._lastRcvMsgId = Number.MAX_SAFE_INTEGER - 1;
69
- /** @private */
70
- this._lastSentMsgId = 0;
71
- /** @private */
72
- this._paused = false;
73
- /** @private */
74
- this._resuming = false;
75
- /** @private */
76
- this._writeBufferSize = 0;
77
- /** @private */
78
- this._bytesRead = 0;
79
- /** @private */
80
- this._bytesWritten = 0;
81
- /** @private */
82
- this._connecting = false;
83
- /** @private */
84
- this._pending = true;
85
- /** @private */
86
- this._destroyed = false;
87
- // TODO: Add readOnly and writeOnly states
88
- /** @type {'opening' | 'open' | 'readOnly' | 'writeOnly'} @private */
89
- this._readyState = 'open'; // Incorrect, but matches NodeJS behavior
90
- /** @type {{ id: number; data: string; }[]} @private */
91
- this._pausedDataEvents = [];
92
- this.readableHighWaterMark = 16384;
93
- this.writableHighWaterMark = 16384;
94
- this.writableNeedDrain = false;
95
- this.localAddress = undefined;
96
- this.localPort = undefined;
97
- this.remoteAddress = undefined;
98
- this.remotePort = undefined;
99
- this.remoteFamily = undefined;
100
- this._registerEvents();
101
- }
102
-
103
- get readyState() {
104
- return this._readyState;
105
- }
106
-
107
- get destroyed() {
108
- return this._destroyed;
109
- }
110
-
111
- get pending() {
112
- return this._pending;
113
- }
114
-
115
- get connecting() {
116
- return this._connecting;
117
- }
118
-
119
- get bytesWritten() {
120
- return this._bytesWritten;
121
- }
122
-
123
- get bytesRead() {
124
- return this._bytesRead;
125
- }
126
-
127
- get timeout() {
128
- return this._timeout;
129
- }
130
-
131
- /**
132
- * @package
133
- * @param {number} id
134
- */
135
- _setId(id) {
136
- this._id = id;
137
- this._registerEvents();
138
- }
139
-
140
- /**
141
- * @package
142
- * @param {NativeConnectionInfo} connectionInfo
143
- */
144
- _setConnected(connectionInfo) {
145
- this._connecting = false;
146
- this._readyState = 'open';
147
- this._pending = false;
148
- this.localAddress = connectionInfo.localAddress;
149
- this.localPort = connectionInfo.localPort;
150
- this.remoteAddress = connectionInfo.remoteAddress;
151
- this.remoteFamily = connectionInfo.remoteFamily;
152
- this.remotePort = connectionInfo.remotePort;
153
- }
154
-
155
- /**
156
- * @param {ConnectionOptions} options
157
- * @param {() => void} [callback]
158
- */
159
- connect(options, callback) {
160
- const customOptions = { ...options };
161
- // Normalize args
162
- customOptions.host = customOptions.host || 'localhost';
163
- customOptions.port = Number(customOptions.port) || 0;
164
- this.once('connect', () => {
165
- if (callback) callback();
166
- });
167
- this._connecting = true;
168
- this._readyState = 'opening';
169
- Sockets.connect(this._id, customOptions.host, customOptions.port, customOptions);
170
- return this;
171
- }
172
-
173
- /**
174
- * Sets the socket to timeout after `timeout` milliseconds of inactivity on the socket. By default `TcpSocket` do not have a timeout.
175
- *
176
- * When an idle timeout is triggered the socket will receive a `'timeout'` event but the connection will not be severed.
177
- * The user must manually call `socket.end()` or `socket.destroy()` to end the connection.
178
- *
179
- * If `timeout` is 0, then the existing idle timeout is disabled.
180
- *
181
- * The optional `callback` parameter will be added as a one-time listener for the `'timeout'` event.
182
- *
183
- * @param {number} timeout
184
- * @param {() => void} [callback]
185
- */
186
- setTimeout(timeout, callback) {
187
- if (timeout === 0) {
188
- this._clearTimeout();
189
- } else {
190
- this._activateTimer(timeout);
191
- }
192
- if (callback) this.once('timeout', callback);
193
- return this;
194
- }
195
-
196
- /**
197
- * @private
198
- * @param {number} [timeout]
199
- */
200
- _activateTimer(timeout) {
201
- if (timeout !== undefined) this._timeoutMsecs = timeout;
202
- this._clearTimeout();
203
- this._timeout = setTimeout(() => {
204
- this._clearTimeout();
205
- this.emit('timeout');
206
- }, this._timeoutMsecs);
207
- }
208
-
209
- /**
210
- * @private
211
- */
212
- _clearTimeout() {
213
- if (this._timeout !== undefined) {
214
- clearTimeout(this._timeout);
215
- this._timeout = undefined;
216
- }
217
- }
218
-
219
- /**
220
- * Set the encoding for the socket as a Readable Stream. By default, no encoding is assigned and stream data will be returned as `Buffer` objects.
221
- * Setting an encoding causes the stream data to be returned as strings of the specified encoding rather than as Buffer objects.
222
- *
223
- * For instance, calling `socket.setEncoding('utf8')` will cause the output data to be interpreted as UTF-8 data, and passed as strings.
224
- * Calling `socket.setEncoding('hex')` will cause the data to be encoded in hexadecimal string format.
225
- *
226
- * @param {BufferEncoding} [encoding]
227
- */
228
- setEncoding(encoding) {
229
- this._encoding = encoding;
230
- return this;
231
- }
232
-
233
- /**
234
- * Enable/disable the use of Nagle's algorithm. When a TCP connection is created, it will have Nagle's algorithm enabled.
235
- *
236
- * Nagle's algorithm delays data before it is sent via the network. It attempts to optimize throughput at the expense of latency.
237
- *
238
- * Passing `true` for `noDelay` or not passing an argument will disable Nagle's algorithm for the socket. Passing false for noDelay will enable Nagle's algorithm.
239
- *
240
- * @param {boolean} noDelay Default: `true`
241
- */
242
- setNoDelay(noDelay = true) {
243
- if (this._pending) {
244
- this.once('connect', () => this.setNoDelay(noDelay));
245
- return this;
246
- }
247
- Sockets.setNoDelay(this._id, noDelay);
248
- return this;
249
- }
250
-
251
- /**
252
- * Enable/disable keep-alive functionality, and optionally set the initial delay before the first keepalive probe is sent on an idle socket.
253
- *
254
- * `initialDelay` is ignored.
255
- *
256
- * @param {boolean} enable Default: `false`
257
- * @param {number} initialDelay ***IGNORED**. Default: `0`
258
- */
259
- setKeepAlive(enable = false, initialDelay = 0) {
260
- if (this._pending) {
261
- this.once('connect', () => this.setKeepAlive(enable, initialDelay));
262
- return this;
263
- }
264
-
265
- if (initialDelay !== 0) {
266
- console.warn(
267
- 'react-native-tcp-socket: initialDelay param in socket.setKeepAlive() is ignored'
268
- );
269
- }
270
-
271
- Sockets.setKeepAlive(this._id, enable, Math.floor(initialDelay));
272
- return this;
273
- }
274
-
275
- /**
276
- * Returns the bound `address`, the address `family` name and `port` of the socket as reported
277
- * by the operating system: `{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`.
278
- *
279
- * @returns {AddressInfo | {}}
280
- */
281
- address() {
282
- if (!this.localAddress) return {};
283
- return { address: this.localAddress, family: this.remoteFamily, port: this.localPort };
284
- }
285
-
286
- /**
287
- * Half-closes the socket. i.e., it sends a FIN packet. It is possible the server will still send some data.
288
- *
289
- * @param {string | Buffer | Uint8Array} [data]
290
- * @param {BufferEncoding} [encoding]
291
- */
292
- end(data, encoding) {
293
- if (data) {
294
- this.write(data, encoding, () => {
295
- Sockets.end(this._id);
296
- });
297
- return this;
298
- }
299
- if (this._pending || this._destroyed) return this;
300
-
301
- this._clearTimeout();
302
- Sockets.end(this._id);
303
- return this;
304
- }
305
-
306
- /**
307
- * Ensures that no more I/O activity happens on this socket. Destroys the stream and closes the connection.
308
- */
309
- destroy() {
310
- if (this._destroyed) return this;
311
- this._destroyed = true;
312
- this._clearTimeout();
313
- Sockets.destroy(this._id);
314
- return this;
315
- }
316
-
317
- /**
318
- * Sends data on the socket. The second parameter specifies the encoding in the case of a string — it defaults to UTF8 encoding.
319
- *
320
- * Returns `true` if the entire data was flushed successfully to the kernel buffer. Returns `false` if all or part of the data
321
- * was queued in user memory. `'drain'` will be emitted when the buffer is again free.
322
- *
323
- * The optional callback parameter will be executed when the data is finally written out, which may not be immediately.
324
- *
325
- * @param {string | Buffer | Uint8Array} buffer
326
- * @param {BufferEncoding} [encoding]
327
- * @param {(err?: Error) => void} [cb]
328
- *
329
- * @return {boolean}
330
- */
331
- write(buffer, encoding, cb) {
332
- const self = this;
333
- if (this._pending || this._destroyed) throw new Error('Socket is closed.');
334
-
335
- const generatedBuffer = this._generateSendBuffer(buffer, encoding);
336
- this._writeBufferSize += generatedBuffer.byteLength;
337
- const currentMsgId = this._msgId;
338
- this._msgId = (this._msgId + 1) % Number.MAX_SAFE_INTEGER;
339
- const msgEvtHandler = (/** @type {{id: number, msgId: number, err?: string}} */ evt) => {
340
- const { msgId, err } = evt;
341
- if (msgId === currentMsgId) {
342
- this._msgEvtEmitter.removeListener('written', msgEvtHandler);
343
- this._writeBufferSize -= generatedBuffer.byteLength;
344
- this._lastRcvMsgId = msgId;
345
- if (self._timeout) self._activateTimer();
346
- if (this.writableNeedDrain && this._lastSentMsgId === msgId) {
347
- this.writableNeedDrain = false;
348
- this.emit('drain');
349
- }
350
- if (cb) {
351
- if (err) cb(new Error(err));
352
- else cb();
353
- }
354
- }
355
- };
356
- // Callback equivalent with better performance
357
- this._msgEvtEmitter.on('written', msgEvtHandler, this);
358
- const ok = this._writeBufferSize < this.writableHighWaterMark;
359
- if (!ok) this.writableNeedDrain = true;
360
- this._lastSentMsgId = currentMsgId;
361
- this._bytesWritten += generatedBuffer.byteLength;
362
- Sockets.write(this._id, generatedBuffer.toString('base64'), currentMsgId);
363
- return ok;
364
- }
365
-
366
- /**
367
- * Pauses the reading of data. That is, `'data'` events will not be emitted. Useful to throttle back an upload.
368
- */
369
- pause() {
370
- if (this._paused) return;
371
- this._paused = true;
372
- Sockets.pause(this._id);
373
- this.emit('pause');
374
- }
375
-
376
- /**
377
- * Resumes reading after a call to `socket.pause()`.
378
- */
379
- resume() {
380
- if (!this._paused) return;
381
- this._paused = false;
382
- this.emit('resume');
383
- this._recoverDataEventsAfterPause();
384
- }
385
-
386
- ref() {
387
- console.warn('react-native-tcp-socket: Socket.ref() method will have no effect.');
388
- }
389
-
390
- unref() {
391
- console.warn('react-native-tcp-socket: Socket.unref() method will have no effect.');
392
- }
393
-
394
- /**
395
- * @private
396
- */
397
- async _recoverDataEventsAfterPause() {
398
- if (this._resuming) return;
399
- this._resuming = true;
400
- while (this._pausedDataEvents.length > 0) {
401
- // Concat all buffered events for better performance
402
- const buffArray = [];
403
- let readBytes = 0;
404
- let i = 0;
405
- for (; i < this._pausedDataEvents.length; i++) {
406
- const evtData = Buffer.from(this._pausedDataEvents[i].data, 'base64');
407
- readBytes += evtData.byteLength;
408
- if (readBytes <= this.readableHighWaterMark) {
409
- buffArray.push(evtData);
410
- } else {
411
- const buffOffset = this.readableHighWaterMark - readBytes;
412
- buffArray.push(evtData.slice(0, buffOffset));
413
- this._pausedDataEvents[i].data = evtData.slice(buffOffset).toString('base64');
414
- break;
415
- }
416
- }
417
- // Generate new event with the concatenated events
418
- const evt = {
419
- id: this._pausedDataEvents[0].id,
420
- data: Buffer.concat(buffArray).toString('base64'),
421
- };
422
- // Clean the old events
423
- this._pausedDataEvents = this._pausedDataEvents.slice(i);
424
- this._onDeviceDataEvt(evt);
425
- if (this._paused) {
426
- this._resuming = false;
427
- return;
428
- }
429
- }
430
- this._resuming = false;
431
- Sockets.resume(this._id);
432
- }
433
-
434
- /**
435
- * @private
436
- */
437
- _onDeviceDataEvt = (/** @type {{ id: number; data: string; }} */ evt) => {
438
- if (evt.id !== this._id) return;
439
- if (!this._paused) {
440
- const bufferData = Buffer.from(evt.data, 'base64');
441
- this._bytesRead += bufferData.byteLength;
442
- const finalData = this._encoding ? bufferData.toString(this._encoding) : bufferData;
443
- this.emit('data', finalData);
444
- } else {
445
- // If the socket is paused, save the data events for later
446
- this._pausedDataEvents.push(evt);
447
- }
448
- };
449
-
450
- /**
451
- * @private
452
- */
453
- _registerEvents() {
454
- this._unregisterEvents();
455
- this._dataListener = this._eventEmitter.addListener('data', this._onDeviceDataEvt);
456
- this._errorListener = this._eventEmitter.addListener('error', (evt) => {
457
- if (evt.id !== this._id) return;
458
- this.destroy();
459
- this.emit('error', evt.error);
460
- });
461
- this._closeListener = this._eventEmitter.addListener('close', (evt) => {
462
- if (evt.id !== this._id) return;
463
- this._setDisconnected();
464
- this.emit('close', evt.error);
465
- });
466
- this._connectListener = this._eventEmitter.addListener('connect', (evt) => {
467
- if (evt.id !== this._id) return;
468
- this._setConnected(evt.connection);
469
- this.emit('connect');
470
- });
471
- this._writtenListener = this._eventEmitter.addListener('written', (evt) => {
472
- if (evt.id !== this._id) return;
473
- this._msgEvtEmitter.emit('written', evt);
474
- });
475
- }
476
-
477
- /**
478
- * @package
479
- */
480
- _unregisterEvents() {
481
- this._dataListener?.remove();
482
- this._errorListener?.remove();
483
- this._closeListener?.remove();
484
- this._connectListener?.remove();
485
- this._writtenListener?.remove();
486
- }
487
-
488
- /**
489
- * @private
490
- * @param {string | Buffer | Uint8Array} buffer
491
- * @param {BufferEncoding} [encoding]
492
- */
493
- _generateSendBuffer(buffer, encoding) {
494
- if (typeof buffer === 'string') {
495
- return Buffer.from(buffer, encoding);
496
- } else if (Buffer.isBuffer(buffer)) {
497
- return buffer;
498
- } else if (buffer instanceof Uint8Array || Array.isArray(buffer)) {
499
- return Buffer.from(buffer);
500
- } else {
501
- throw new TypeError(
502
- `Invalid data, chunk must be a string or buffer, not ${typeof buffer}`
503
- );
504
- }
505
- }
506
-
507
- /**
508
- * @private
509
- */
510
- _setDisconnected() {
511
- this._unregisterEvents();
512
- }
513
- }
1
+ 'use strict';
2
+
3
+ import EventEmitter from 'eventemitter3';
4
+ import { Buffer } from 'buffer';
5
+ import { TurboModuleRegistry, NativeModules } from 'react-native';
6
+ import { nativeEventEmitter, getNextId } from './Globals';
7
+
8
+ const Sockets = TurboModuleRegistry ? TurboModuleRegistry.get('TcpSocketModule') : NativeModules.TcpSockets;
9
+
10
+
11
+ /**
12
+ * @typedef {"ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "latin1" | "binary" | "hex"} BufferEncoding
13
+ *
14
+ * @typedef {import('react-native').NativeEventEmitter} NativeEventEmitter
15
+ *
16
+ * @typedef {{address: string, family: string, port: number}} AddressInfo
17
+ *
18
+ * @typedef {{localAddress: string, localPort: number, remoteAddress: string, remotePort: number, remoteFamily: string}} NativeConnectionInfo
19
+ *
20
+ * @typedef {{
21
+ * port: number;
22
+ * host?: string;
23
+ * localAddress?: string,
24
+ * localPort?: number,
25
+ * interface?: 'wifi' | 'cellular' | 'ethernet',
26
+ * reuseAddress?: boolean,
27
+ * tls?: boolean,
28
+ * tlsCheckValidity?: boolean,
29
+ * tlsCert?: any,
30
+ * }} ConnectionOptions
31
+ *
32
+ * @typedef {object} ReadableEvents
33
+ * @property {() => void} pause
34
+ * @property {() => void} resume
35
+ *
36
+ * @typedef {object} SocketEvents
37
+ * @property {(had_error: boolean) => void} close
38
+ * @property {() => void} connect
39
+ * @property {(data: Buffer | string) => void} data
40
+ * @property {() => void} drain
41
+ * @property {(err: Error) => void} error
42
+ * @property {() => void} timeout
43
+ * @property {() => void} secureConnect
44
+ *
45
+ * @extends {EventEmitter<SocketEvents & ReadableEvents, any>}
46
+ */
47
+ export default class Socket extends EventEmitter {
48
+ /**
49
+ * Creates a new socket object.
50
+ */
51
+ constructor() {
52
+ super();
53
+ /** @package */
54
+ this._id = getNextId();
55
+ /** @private */
56
+ this._eventEmitter = nativeEventEmitter;
57
+ /** @type {EventEmitter<'written', any>} @private */
58
+ this._msgEvtEmitter = new EventEmitter();
59
+ /** @type {number} @private */
60
+ this._timeoutMsecs = 0;
61
+ /** @type {number | undefined} @private */
62
+ this._timeout = undefined;
63
+ /** @private */
64
+ this._encoding = undefined;
65
+ /** @private */
66
+ this._msgId = 0;
67
+ /** @private */
68
+ this._lastRcvMsgId = Number.MAX_SAFE_INTEGER - 1;
69
+ /** @private */
70
+ this._lastSentMsgId = 0;
71
+ /** @private */
72
+ this._paused = false;
73
+ /** @private */
74
+ this._resuming = false;
75
+ /** @private */
76
+ this._writeBufferSize = 0;
77
+ /** @private */
78
+ this._bytesRead = 0;
79
+ /** @private */
80
+ this._bytesWritten = 0;
81
+ /** @private */
82
+ this._connecting = false;
83
+ /** @private */
84
+ this._pending = true;
85
+ /** @private */
86
+ this._destroyed = false;
87
+ // TODO: Add readOnly and writeOnly states
88
+ /** @type {'opening' | 'open' | 'readOnly' | 'writeOnly'} @private */
89
+ this._readyState = 'open'; // Incorrect, but matches NodeJS behavior
90
+ /** @type {{ id: number; data: string; }[]} @private */
91
+ this._pausedDataEvents = [];
92
+ this.readableHighWaterMark = 16384;
93
+ this.writableHighWaterMark = 16384;
94
+ this.writableNeedDrain = false;
95
+ this.localAddress = undefined;
96
+ this.localPort = undefined;
97
+ this.remoteAddress = undefined;
98
+ this.remotePort = undefined;
99
+ this.remoteFamily = undefined;
100
+ this._registerEvents();
101
+ }
102
+
103
+ get readyState() {
104
+ return this._readyState;
105
+ }
106
+
107
+ get destroyed() {
108
+ return this._destroyed;
109
+ }
110
+
111
+ get pending() {
112
+ return this._pending;
113
+ }
114
+
115
+ get connecting() {
116
+ return this._connecting;
117
+ }
118
+
119
+ get bytesWritten() {
120
+ return this._bytesWritten;
121
+ }
122
+
123
+ get bytesRead() {
124
+ return this._bytesRead;
125
+ }
126
+
127
+ get timeout() {
128
+ return this._timeout;
129
+ }
130
+
131
+ /**
132
+ * @package
133
+ * @param {number} id
134
+ */
135
+ _setId(id) {
136
+ this._id = id;
137
+ this._registerEvents();
138
+ }
139
+
140
+ /**
141
+ * @package
142
+ * @param {NativeConnectionInfo} connectionInfo
143
+ */
144
+ _setConnected(connectionInfo) {
145
+ this._connecting = false;
146
+ this._readyState = 'open';
147
+ this._pending = false;
148
+ this.localAddress = connectionInfo.localAddress;
149
+ this.localPort = connectionInfo.localPort;
150
+ this.remoteAddress = connectionInfo.remoteAddress;
151
+ this.remoteFamily = connectionInfo.remoteFamily;
152
+ this.remotePort = connectionInfo.remotePort;
153
+ }
154
+
155
+ /**
156
+ * @param {ConnectionOptions} options
157
+ * @param {() => void} [callback]
158
+ */
159
+ connect(options, callback) {
160
+ const customOptions = { ...options };
161
+ // Normalize args
162
+ customOptions.host = customOptions.host || 'localhost';
163
+ customOptions.port = Number(customOptions.port) || 0;
164
+ this.once('connect', () => {
165
+ if (callback) callback();
166
+ });
167
+ this._connecting = true;
168
+ this._readyState = 'opening';
169
+ Sockets.connect(this._id, customOptions.host, customOptions.port, customOptions);
170
+ return this;
171
+ }
172
+
173
+ /**
174
+ * Sets the socket to timeout after `timeout` milliseconds of inactivity on the socket. By default `TcpSocket` do not have a timeout.
175
+ *
176
+ * When an idle timeout is triggered the socket will receive a `'timeout'` event but the connection will not be severed.
177
+ * The user must manually call `socket.end()` or `socket.destroy()` to end the connection.
178
+ *
179
+ * If `timeout` is 0, then the existing idle timeout is disabled.
180
+ *
181
+ * The optional `callback` parameter will be added as a one-time listener for the `'timeout'` event.
182
+ *
183
+ * @param {number} timeout
184
+ * @param {() => void} [callback]
185
+ */
186
+ setTimeout(timeout, callback) {
187
+ if (timeout === 0) {
188
+ this._clearTimeout();
189
+ } else {
190
+ this._activateTimer(timeout);
191
+ }
192
+ if (callback) this.once('timeout', callback);
193
+ return this;
194
+ }
195
+
196
+ /**
197
+ * @private
198
+ * @param {number} [timeout]
199
+ */
200
+ _activateTimer(timeout) {
201
+ if (timeout !== undefined) this._timeoutMsecs = timeout;
202
+ this._clearTimeout();
203
+ this._timeout = setTimeout(() => {
204
+ this._clearTimeout();
205
+ this.emit('timeout');
206
+ }, this._timeoutMsecs);
207
+ }
208
+
209
+ /**
210
+ * @private
211
+ */
212
+ _clearTimeout() {
213
+ if (this._timeout !== undefined) {
214
+ clearTimeout(this._timeout);
215
+ this._timeout = undefined;
216
+ }
217
+ }
218
+
219
+ /**
220
+ * Set the encoding for the socket as a Readable Stream. By default, no encoding is assigned and stream data will be returned as `Buffer` objects.
221
+ * Setting an encoding causes the stream data to be returned as strings of the specified encoding rather than as Buffer objects.
222
+ *
223
+ * For instance, calling `socket.setEncoding('utf8')` will cause the output data to be interpreted as UTF-8 data, and passed as strings.
224
+ * Calling `socket.setEncoding('hex')` will cause the data to be encoded in hexadecimal string format.
225
+ *
226
+ * @param {BufferEncoding} [encoding]
227
+ */
228
+ setEncoding(encoding) {
229
+ this._encoding = encoding;
230
+ return this;
231
+ }
232
+
233
+ /**
234
+ * Enable/disable the use of Nagle's algorithm. When a TCP connection is created, it will have Nagle's algorithm enabled.
235
+ *
236
+ * Nagle's algorithm delays data before it is sent via the network. It attempts to optimize throughput at the expense of latency.
237
+ *
238
+ * Passing `true` for `noDelay` or not passing an argument will disable Nagle's algorithm for the socket. Passing false for noDelay will enable Nagle's algorithm.
239
+ *
240
+ * @param {boolean} noDelay Default: `true`
241
+ */
242
+ setNoDelay(noDelay = true) {
243
+ if (this._pending) {
244
+ this.once('connect', () => this.setNoDelay(noDelay));
245
+ return this;
246
+ }
247
+ Sockets.setNoDelay(this._id, noDelay);
248
+ return this;
249
+ }
250
+
251
+ /**
252
+ * Enable/disable keep-alive functionality, and optionally set the initial delay before the first keepalive probe is sent on an idle socket.
253
+ *
254
+ * `initialDelay` is ignored.
255
+ *
256
+ * @param {boolean} enable Default: `false`
257
+ * @param {number} initialDelay ***IGNORED**. Default: `0`
258
+ */
259
+ setKeepAlive(enable = false, initialDelay = 0) {
260
+ if (this._pending) {
261
+ this.once('connect', () => this.setKeepAlive(enable, initialDelay));
262
+ return this;
263
+ }
264
+
265
+ if (initialDelay !== 0) {
266
+ console.warn(
267
+ 'react-native-tcp-socket: initialDelay param in socket.setKeepAlive() is ignored'
268
+ );
269
+ }
270
+
271
+ Sockets.setKeepAlive(this._id, enable, Math.floor(initialDelay));
272
+ return this;
273
+ }
274
+
275
+ /**
276
+ * Returns the bound `address`, the address `family` name and `port` of the socket as reported
277
+ * by the operating system: `{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`.
278
+ *
279
+ * @returns {AddressInfo | {}}
280
+ */
281
+ address() {
282
+ if (!this.localAddress) return {};
283
+ return { address: this.localAddress, family: this.remoteFamily, port: this.localPort };
284
+ }
285
+
286
+ /**
287
+ * Half-closes the socket. i.e., it sends a FIN packet. It is possible the server will still send some data.
288
+ *
289
+ * @param {string | Buffer | Uint8Array} [data]
290
+ * @param {BufferEncoding} [encoding]
291
+ */
292
+ end(data, encoding) {
293
+ if (data) {
294
+ this.write(data, encoding, () => {
295
+ Sockets.end(this._id);
296
+ });
297
+ return this;
298
+ }
299
+ if (this._pending || this._destroyed) return this;
300
+
301
+ this._clearTimeout();
302
+ Sockets.end(this._id);
303
+ return this;
304
+ }
305
+
306
+ /**
307
+ * Ensures that no more I/O activity happens on this socket. Destroys the stream and closes the connection.
308
+ */
309
+ destroy() {
310
+ if (this._destroyed) return this;
311
+ this._destroyed = true;
312
+ this._clearTimeout();
313
+ Sockets.destroy(this._id);
314
+ return this;
315
+ }
316
+
317
+ /**
318
+ * Sends data on the socket. The second parameter specifies the encoding in the case of a string — it defaults to UTF8 encoding.
319
+ *
320
+ * Returns `true` if the entire data was flushed successfully to the kernel buffer. Returns `false` if all or part of the data
321
+ * was queued in user memory. `'drain'` will be emitted when the buffer is again free.
322
+ *
323
+ * The optional callback parameter will be executed when the data is finally written out, which may not be immediately.
324
+ *
325
+ * @param {string | Buffer | Uint8Array} buffer
326
+ * @param {BufferEncoding} [encoding]
327
+ * @param {(err?: Error) => void} [cb]
328
+ *
329
+ * @return {boolean}
330
+ */
331
+ write(buffer, encoding, cb) {
332
+ const self = this;
333
+ if (this._pending || this._destroyed) throw new Error('Socket is closed.');
334
+
335
+ const generatedBuffer = this._generateSendBuffer(buffer, encoding);
336
+ this._writeBufferSize += generatedBuffer.byteLength;
337
+ const currentMsgId = this._msgId;
338
+ this._msgId = (this._msgId + 1) % Number.MAX_SAFE_INTEGER;
339
+ const msgEvtHandler = (/** @type {{id: number, msgId: number, err?: string}} */ evt) => {
340
+ const { msgId, err } = evt;
341
+ if (msgId === currentMsgId) {
342
+ this._msgEvtEmitter.removeListener('written', msgEvtHandler);
343
+ this._writeBufferSize -= generatedBuffer.byteLength;
344
+ this._lastRcvMsgId = msgId;
345
+ if (self._timeout) self._activateTimer();
346
+ if (this.writableNeedDrain && this._lastSentMsgId === msgId) {
347
+ this.writableNeedDrain = false;
348
+ this.emit('drain');
349
+ }
350
+ if (cb) {
351
+ if (err) cb(new Error(err));
352
+ else cb();
353
+ }
354
+ }
355
+ };
356
+ // Callback equivalent with better performance
357
+ this._msgEvtEmitter.on('written', msgEvtHandler, this);
358
+ const ok = this._writeBufferSize < this.writableHighWaterMark;
359
+ if (!ok) this.writableNeedDrain = true;
360
+ this._lastSentMsgId = currentMsgId;
361
+ this._bytesWritten += generatedBuffer.byteLength;
362
+ Sockets.write(this._id, generatedBuffer.toString('base64'), currentMsgId);
363
+ return ok;
364
+ }
365
+
366
+ /**
367
+ * Pauses the reading of data. That is, `'data'` events will not be emitted. Useful to throttle back an upload.
368
+ */
369
+ pause() {
370
+ if (this._paused) return;
371
+ this._paused = true;
372
+ Sockets.pause(this._id);
373
+ this.emit('pause');
374
+ }
375
+
376
+ /**
377
+ * Resumes reading after a call to `socket.pause()`.
378
+ */
379
+ resume() {
380
+ if (!this._paused) return;
381
+ this._paused = false;
382
+ this.emit('resume');
383
+ this._recoverDataEventsAfterPause();
384
+ }
385
+
386
+ ref() {
387
+ console.warn('react-native-tcp-socket: Socket.ref() method will have no effect.');
388
+ }
389
+
390
+ unref() {
391
+ console.warn('react-native-tcp-socket: Socket.unref() method will have no effect.');
392
+ }
393
+
394
+ /**
395
+ * @private
396
+ */
397
+ async _recoverDataEventsAfterPause() {
398
+ if (this._resuming) return;
399
+ this._resuming = true;
400
+ while (this._pausedDataEvents.length > 0) {
401
+ // Concat all buffered events for better performance
402
+ const buffArray = [];
403
+ let readBytes = 0;
404
+ let i = 0;
405
+ for (; i < this._pausedDataEvents.length; i++) {
406
+ const evtData = Buffer.from(this._pausedDataEvents[i].data, 'base64');
407
+ readBytes += evtData.byteLength;
408
+ if (readBytes <= this.readableHighWaterMark) {
409
+ buffArray.push(evtData);
410
+ } else {
411
+ const buffOffset = this.readableHighWaterMark - readBytes;
412
+ buffArray.push(evtData.slice(0, buffOffset));
413
+ this._pausedDataEvents[i].data = evtData.slice(buffOffset).toString('base64');
414
+ break;
415
+ }
416
+ }
417
+ // Generate new event with the concatenated events
418
+ const evt = {
419
+ id: this._pausedDataEvents[0].id,
420
+ data: Buffer.concat(buffArray).toString('base64'),
421
+ };
422
+ // Clean the old events
423
+ this._pausedDataEvents = this._pausedDataEvents.slice(i);
424
+ this._onDeviceDataEvt(evt);
425
+ if (this._paused) {
426
+ this._resuming = false;
427
+ return;
428
+ }
429
+ }
430
+ this._resuming = false;
431
+ Sockets.resume(this._id);
432
+ }
433
+
434
+ /**
435
+ * @private
436
+ */
437
+ _onDeviceDataEvt = (/** @type {{ id: number; data: string; }} */ evt) => {
438
+ if (evt.id !== this._id) return;
439
+ if (!this._paused) {
440
+ const bufferData = Buffer.from(evt.data, 'base64');
441
+ this._bytesRead += bufferData.byteLength;
442
+ const finalData = this._encoding ? bufferData.toString(this._encoding) : bufferData;
443
+ this.emit('data', finalData);
444
+ } else {
445
+ // If the socket is paused, save the data events for later
446
+ this._pausedDataEvents.push(evt);
447
+ }
448
+ };
449
+
450
+ /**
451
+ * @private
452
+ */
453
+ _registerEvents() {
454
+ this._unregisterEvents();
455
+ this._dataListener = this._eventEmitter.addListener('data', this._onDeviceDataEvt);
456
+ this._errorListener = this._eventEmitter.addListener('error', (evt) => {
457
+ if (evt.id !== this._id) return;
458
+ this.destroy();
459
+ this.emit('error', evt.error);
460
+ });
461
+ this._closeListener = this._eventEmitter.addListener('close', (evt) => {
462
+ if (evt.id !== this._id) return;
463
+ this._setDisconnected();
464
+ this.emit('close', evt.error);
465
+ });
466
+ this._connectListener = this._eventEmitter.addListener('connect', (evt) => {
467
+ if (evt.id !== this._id) return;
468
+ this._setConnected(evt.connection);
469
+ this.emit('connect');
470
+ });
471
+ this._writtenListener = this._eventEmitter.addListener('written', (evt) => {
472
+ if (evt.id !== this._id) return;
473
+ this._msgEvtEmitter.emit('written', evt);
474
+ });
475
+ }
476
+
477
+ /**
478
+ * @package
479
+ */
480
+ _unregisterEvents() {
481
+ this._dataListener?.remove();
482
+ this._errorListener?.remove();
483
+ this._closeListener?.remove();
484
+ this._connectListener?.remove();
485
+ this._writtenListener?.remove();
486
+ }
487
+
488
+ /**
489
+ * @private
490
+ * @param {string | Buffer | Uint8Array} buffer
491
+ * @param {BufferEncoding} [encoding]
492
+ */
493
+ _generateSendBuffer(buffer, encoding) {
494
+ if (typeof buffer === 'string') {
495
+ return Buffer.from(buffer, encoding);
496
+ } else if (Buffer.isBuffer(buffer)) {
497
+ return buffer;
498
+ } else if (buffer instanceof Uint8Array || Array.isArray(buffer)) {
499
+ return Buffer.from(buffer);
500
+ } else {
501
+ throw new TypeError(
502
+ `Invalid data, chunk must be a string or buffer, not ${typeof buffer}`
503
+ );
504
+ }
505
+ }
506
+
507
+ /**
508
+ * @private
509
+ */
510
+ _setDisconnected() {
511
+ this._unregisterEvents();
512
+ }
513
+ }