react-native-tcp/TcpServer.js

105 lines
2.5 KiB
JavaScript
Raw Normal View History

2015-12-23 18:56:33 +00:00
/**
* Copyright (c) 2015-present, Peel Technologies, Inc.
* All rights reserved.
*
* @providesModule TcpServer
* @flow
*/
'use strict';
var inherits = require('inherits');
var EventEmitter = require('events').EventEmitter;
var {
NativeModules
} = require('react-native');
var Sockets = NativeModules.TcpSockets;
var Socket = require('./TcpSocket');
2015-12-24 19:18:51 +00:00
function TcpServer(connectionListener: (socket: Socket) => void) {
2015-12-23 18:56:33 +00:00
if (!(this instanceof TcpServer)) {
return new TcpServer(connectionListener);
}
if (EventEmitter instanceof Function) {
EventEmitter.call(this);
}
2015-12-23 18:56:33 +00:00
var self = this;
this._socket = new Socket();
2015-12-23 18:56:33 +00:00
// $FlowFixMe: suppressing this error flow doesn't like EventEmitter
this._socket.on('connect', function() {
self.emit('listening');
});
// $FlowFixMe: suppressing this error flow doesn't like EventEmitter
2015-12-24 19:18:51 +00:00
this._socket.on('connection', function(socket) {
self._connections++;
self.emit('connection', socket);
2015-12-23 18:56:33 +00:00
});
// $FlowFixMe: suppressing this error flow doesn't like EventEmitter
this._socket.on('close', function() {
self.emit('close');
});
// $FlowFixMe: suppressing this error flow doesn't like EventEmitter
2015-12-24 19:18:51 +00:00
this._socket.on('error', function(error) {
self.emit('error', error);
2015-12-23 18:56:33 +00:00
});
2015-12-23 23:14:41 +00:00
if (typeof connectionListener === 'function') {
2015-12-23 18:56:33 +00:00
self.on('connection', connectionListener);
}
this._connections = 0;
}
inherits(TcpServer, EventEmitter);
TcpServer.prototype._debug = function() {
if (__DEV__) {
var args = [].slice.call(arguments);
console.log.apply(console, args);
}
};
// TODO : determine how to properly overload this with flow
TcpServer.prototype.listen = function() : TcpServer {
var args = this._socket._normalizeConnectArgs(arguments);
var options = args[0];
var callback = args[1];
2015-12-23 23:14:41 +00:00
var port = options.port;
var host = options.host || 'localhost';
2015-12-23 18:56:33 +00:00
if (callback) {
this.on('listening', callback);
}
this._socket._registerEvents();
Sockets.listen(this._socket._id, host, port);
2015-12-23 18:56:33 +00:00
return this;
};
TcpServer.prototype.getConnections = function(callback: (err: ?any, count: number) => void) {
if (typeof callback === 'function') {
callback.invoke(null, this._connections);
}
};
2015-12-23 23:14:41 +00:00
TcpServer.prototype.address = function() : { port: number, address: string, family: string } {
return this._socket.address();
};
2015-12-23 18:56:33 +00:00
TcpServer.prototype.close = function(callback: ?() => void) {
if (callback) {
this.on('close', callback);
}
this._socket.end();
};
module.exports = TcpServer;