Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Switch to NodeJS's EventEmitter as parent class #55

Merged
merged 4 commits into from
Jun 16, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"parser": "babel-eslint",
"plugins": ["prettier", "jest", "jsdoc"],
"env": {
"es6": true,
Expand Down
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,3 @@ buck-out/

# Tests
coverage
!coverage/coverage-final.json
4 changes: 0 additions & 4 deletions coverage/coverage-final.json

This file was deleted.

6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,9 @@
"@semantic-release/npm": "^7.0.0",
"@types/jest": "^25.1.3",
"@types/react-native": "^0.61.17",
"babel-eslint": "^10.1.0",
"babel-jest": "^24.9.0",
"eslint": "^6.6.0",
"eslint": "^6.8.0",
"eslint-config-prettier": "^6.5.0",
"eslint-plugin-jest": "^23.6.0",
"eslint-plugin-jsdoc": "^21.0.0",
Expand All @@ -74,6 +75,7 @@
"typescript": "^3.8.2"
},
"dependencies": {
"buffer": "^5.4.3"
"buffer": "^5.4.3",
"events": "^3.1.0"
}
}
59 changes: 31 additions & 28 deletions src/TcpServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,56 +18,59 @@ export default class TcpServer extends TcpSocket {
this._eventEmitter = eventEmitter;
}

close() {
this.destroy();
this._connections.forEach((clientSocket) => clientSocket.destroy());
/**
* @override
*/
_registerEvents() {
super._registerEvents();
this._connectionsListener = this._eventEmitter.addListener('connection', (evt) => {
if (evt.id !== this._id) return;
this._onConnection(evt.info);
this.emit('connection', evt.info);
});
}

/**
* @param {(arg0: number) => void} callback
* @override
*/
getConnections(callback) {
callback(this._connections.length);
_unregisterEvents() {
super._unregisterEvents();
this._connectionsListener?.remove();
}

/**
* @param {{ port: number; host: any; }} options
* @param {(arg0: any) => void} callback
* @param {{ port: number; host: string; reuseAddress?: boolean}} options
* @param {(arg0: any) => void} [callback]
* @returns {TcpServer}
*/
listen(options, callback) {
let gotOptions = {};
// Normalize args
if (typeof arguments[0] === 'number') {
// Deprecated old version: listen(port[, host][, callback])
console.warn(
'TcpServer.listen(port[, host][, callback]) is deprecated and has been moved to TcpServer.listen(options[, callback]). It will be removed in [email protected]'
);
gotOptions.port = arguments[0];
/** @type {string} */
gotOptions.host = arguments[1];
callback = arguments[2];
} else {
gotOptions = options;
}
const gotOptions = { ...options };
gotOptions.host = gotOptions.host || '0.0.0.0';
const connectListener = this.on('connect', (ev) => {
connectListener.remove();
this.once('connect', (ev) => {
if (callback) callback(ev.address);
});
this._registerEvents();
this.on('connection', (ev) => this._onConnection(ev.info));
Sockets.listen(this._id, gotOptions);
return this;
}

/**
* @param {(arg0: number) => void} callback
*/
getConnections(callback) {
callback(this._connections.length);
}

close() {
this.destroy();
this._connections.forEach((clientSocket) => clientSocket.destroy());
}

/**
* @private
* @param {{ id: number; address: string; }} info
*/
_onConnection(info) {
const socket = new TcpSocket(info.id, this._eventEmitter);
socket.setAsAlreadyConnected(info.address);
const socket = new TcpSocket(info.id, this._eventEmitter, info.address);
this._connections.push(socket);
this.connectionCallback(socket);
}
Expand Down
155 changes: 41 additions & 114 deletions src/TcpSocket.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';

import { NativeModules, Image } from 'react-native';
import { EventEmitter } from 'events';
const Buffer = (global.Buffer = global.Buffer || require('buffer').Buffer);
const Sockets = NativeModules.TcpSockets;

Expand All @@ -10,27 +11,6 @@ const STATE = {
CONNECTED: 2,
};

class RemovableListener {
/**
* @param {import("react-native").EmitterSubscription} listener
* @param {import("react-native").NativeEventEmitter} eventEmitter
*/
constructor(listener, eventEmitter) {
this._listener = listener;
this._eventEmitter = eventEmitter;
this._removed = false;
}

isRemoved() {
return this._removed;
}

remove() {
this._eventEmitter.removeSubscription(this._listener);
this._removed = true;
}
}

/**
* @typedef {{
* port: number;
Expand All @@ -45,99 +25,71 @@ class RemovableListener {
* tlsCert?: any,
* }} ConnectionOptions
*/
export default class TcpSocket {
export default class TcpSocket extends EventEmitter {
/**
* Initialices a TcpSocket.
*
* @param {number} id
* @param {import('react-native').NativeEventEmitter} eventEmitter
* @param {string} [address]
*/
constructor(id, eventEmitter) {
constructor(id, eventEmitter, address) {
super();
this._id = id;
this._eventEmitter = eventEmitter;
/** @type {number} */
this._state = STATE.DISCONNECTED;
/** @type {RemovableListener[]} */
this._listeners = [];
}

/**
* Adds a listener to be invoked when events of the specified type are emitted by the `TcpSocket`.
* An optional calling `context` may be provided.
* The data arguments emitted will be passed to the listener callback.
*
* @param {string} event Name of the event to listen to
* @param {(arg0: any) => void} callback Function to invoke when the specified event is emitted
* @param {any} [context] Optional context object to use when invoking the listener
* @returns {RemovableListener}
*/
on(event, callback, context) {
const newListener = this._selectListener(event, callback, context);
const removableListener = new RemovableListener(newListener, this._eventEmitter);
this._listeners.push(removableListener);
return removableListener;
this._registerEvents();
if (address != undefined) this._setConnected(address);
}

/**
* @private
* @param {string} event
* @param {function(any):void} callback
* @param {any} [context]
* @protected
*/
_selectListener(event, callback, context) {
switch (event) {
case 'data':
return this._eventEmitter.addListener(
'data',
(evt) => {
if (evt.id !== this._id) return;
const bufferTest = Buffer.from(evt.data, 'base64');
callback(bufferTest);
},
context
);
case 'error':
return this._eventEmitter.addListener(
'error',
(evt) => {
if (evt.id !== this._id) return;
callback(evt.error);
},
context
);
default:
return this._eventEmitter.addListener(
event,
(evt) => {
if (evt.id !== this._id) return;
callback(evt);
},
context
);
}
_registerEvents() {
this._unregisterEvents();
this._dataListener = this._eventEmitter.addListener('data', (evt) => {
if (evt.id !== this._id) return;
const bufferTest = Buffer.from(evt.data, 'base64');
this.emit('data', bufferTest);
});
this._errorListener = this._eventEmitter.addListener('error', (evt) => {
if (evt.id !== this._id) return;
this._onError();
this.emit('error', evt.error);
});
this._closeListener = this._eventEmitter.addListener('close', (evt) => {
if (evt.id !== this._id) return;
this._onClose();
this.emit('close', evt.error);
});
this._connectListener = this._eventEmitter.addListener('connect', (evt) => {
if (evt.id !== this._id) return;
this._onConnect(evt.address);
this.emit('connect', evt.address);
});
}

/**
* @deprecated
* @protected
*/
off() {
console.warn(
'TCPSocket.off() is deprecated and produces no effect, please use the listener remove() method instead.'
);
_unregisterEvents() {
this._dataListener?.remove();
this._errorListener?.remove();
this._closeListener?.remove();
this._connectListener?.remove();
}

/**
* @param {ConnectionOptions} options
* @param {(address: string) => void} [callback]
*/
connect(options, callback) {
this._registerEvents();
const customOptions = { ...options };
// Normalize args
customOptions.host = customOptions.host || 'localhost';
customOptions.port = Number(customOptions.port) || 0;
const connectListener = this.on('connect', (ev) => {
connectListener.remove();
this.once('connect', (ev) => {
if (callback) callback(ev.address);
});
// Timeout
Expand Down Expand Up @@ -246,36 +198,19 @@ export default class TcpSocket {
}
}

/**
* @protected
*/
_registerEvents() {
this.on('connect', (ev) => this._onConnect(ev.address));
this.on('close', () => this._onClose());
this.on('error', () => this._onError());
}

/**
* @private
*/
_unregisterEvents() {
this._listeners.forEach((listener) => (listener.isRemoved() ? listener.remove() : null));
this._listeners = [];
}

/**
* @private
* @param {string} address
*/
_onConnect(address) {
this.setConnected(address);
this._setConnected(address);
}

/**
* @private
*/
_onClose() {
this.setDisconnected();
this._setDisconnected();
}

/**
Expand Down Expand Up @@ -316,14 +251,6 @@ export default class TcpSocket {
);
}

/**
* @param {string} address
*/
setAsAlreadyConnected(address) {
this._registerEvents();
this.setConnected(address);
}

/**
* @private
* @param {string | Buffer | Uint8Array} buffer
Expand All @@ -347,15 +274,15 @@ export default class TcpSocket {
* @private
* @param {string} address
*/
setConnected(address) {
_setConnected(address) {
this._state = STATE.CONNECTED;
this._address = address;
}

/**
* @private
*/
setDisconnected() {
_setDisconnected() {
if (this._state === STATE.DISCONNECTED) return;
this._unregisterEvents();
this._state = STATE.DISCONNECTED;
Expand Down
Loading