add address function

This commit is contained in:
Andy Prock 2015-12-23 15:14:41 -08:00
parent d2e7b7c555
commit 45066f0a17
7 changed files with 63 additions and 35 deletions

View File

@ -45,11 +45,11 @@ function TcpServer(connectionListener: (socket: Socket) => void) {
this._socket.on('connection', function(socketId) {
self._connections++;
var socket = new Socket({ _id: socketId });
var socket = new Socket({ id: socketId });
self.emit('connection', socket);
});
if (connectionListener === typeof 'function') {
if (typeof connectionListener === 'function') {
self.on('connection', connectionListener);
}
@ -66,7 +66,7 @@ TcpServer.prototype._debug = function() {
};
TcpServer.prototype.listen = function(options: { port: number, hostname: ?string }, callback: ?() => void) : TcpServer {
var port = Number(options.port);
var port = options.port;
var hostname = options.hostname || 'localhost';
if (callback) {
@ -84,6 +84,10 @@ TcpServer.prototype.getConnections = function(callback: (err: ?any, count: numbe
}
};
TcpServer.prototype.address = function() : { port: number, address: string, family: string } {
return this._socket.address();
};
TcpServer.prototype.close = function(callback: ?() => void) {
if (callback) {
this.on('close', callback);

View File

@ -26,29 +26,26 @@ var STATE = {
CONNECTED: 2
};
function TcpSocket(options: ?any) {
function TcpSocket(options: ?{ id: ?number }) {
// $FlowFixMe: suppressing this error flow doesn't like EventEmitter
EventEmitter.call(this);
options = options || {};
var nativeSocket = false;
if (!options._id) {
if (options && options.id) {
// native generated sockets range from 5000-6000
// e.g. incoming server connections
this._id = Number(options.id);
nativeSocket = true;
} else {
// javascript generated sockets range from 1-1000
this._id = Math.floor((Math.random() * 1000) + 1);
while (usedIds.indexOf(this._id) !== -1) {
this._id = Math.floor((Math.random() * 1000) + 1);
}
} else {
// native generated sockets range from 5000-6000
// e.g. incoming server connections
this._id = options._id;
nativeSocket = true;
}
usedIds.push(this._id);
this._state = nativeSocket ? STATE.CONNECTED : STATE.DISCONNECTED;
this._host = null;
this._state = STATE.CONNECTED;
// these will be set once there is a connection
this.readable = this.writable = false;
@ -63,6 +60,7 @@ function TcpSocket(options: ?any) {
}
if (nativeSocket === false) {
this._state = STATE.DISCONNECTED;
Sockets.createSocket(this._id);
}
}
@ -174,8 +172,10 @@ TcpSocket.prototype.unref = function() {
// nothing yet
};
TcpSocket.prototype.address = function() {
// nothing yet
TcpSocket.prototype.address = function() : { port: number, address: string, family: string } {
return { port: this._port,
address: this._address,
family: this._family };
};
TcpSocket.prototype.end = function(data, encoding) {
@ -204,12 +204,16 @@ TcpSocket.prototype.destroy = function() {
}
};
TcpSocket.prototype._onEvent = function(info: { event: string, data: ?any }) {
TcpSocket.prototype._onEvent = function(info: { event: string, data: any }) {
this._debug('received', info.event);
if (info.event === 'connect') {
this.writable = this.readable = true;
this._state = STATE.CONNECTED;
this._address = info.data.address;
this._port = Number(info.data.port);
this._family = info.data.family;
} else if (info.event === 'data') {
if (this._timeout) {
clearTimeout(this._timeout);

View File

@ -21,9 +21,9 @@ function randomPort() {
return Math.random() * 60536 | 0 + 5000; // 60536-65536
}
var aPort = randomPort();
var serverPort = randomPort();
var a = net.createServer({}, function(socket) {
var server = net.createServer(function(socket) {
console.log('server connected');
socket.on('data', function (data) {
@ -34,21 +34,19 @@ var a = net.createServer({}, function(socket) {
socket.on('error', function(error) {
console.log('error ' + error);
});
}).listen({ port: aPort });
var b = net.createConnection({ port: aPort }, function(err) {
if (err) {
throw err;
}
console.log('client connected');
b.write('Hello, server! Love, Client.');
}).listen({ port: serverPort }, function() {
console.log('opened server on ' + JSON.stringify(server.address()));
});
b.on('data', function(data) {
var client = net.createConnection({ port: serverPort }, function() {
console.log('opened client on ' + JSON.stringify(client.address()));
client.write('Hello, server! Love, Client.');
});
client.on('data', function(data) {
console.log('Client Received: ' + data);
b.end(); // kill client after server's response
a.close();
client.destroy(); // kill client after server's response
server.close();
});
var rctsockets = React.createClass({

View File

@ -67,6 +67,8 @@ typedef enum RCTTCPError RCTTCPError;
- (BOOL)listen:(NSString *)host port:(int)port error:(NSError **)error;
- (NSDictionary<NSString *, NSString *> *)getAddress;
/**
* write data
*

View File

@ -85,6 +85,26 @@ NSString *const RCTTCPErrorDomain = @"RCTTCPErrorDomain";
return result;
}
- (NSDictionary<NSString *, NSString *> *)getAddress
{
if (_tcpSocket)
{
if (_tcpSocket.isConnected) {
return @{ @"port": @(_tcpSocket.connectedPort).stringValue,
@"address": _tcpSocket.connectedHost ?: @"unknown",
@"family": _tcpSocket.isIPv6?@"IPv6":@"IPv4" };
} else {
return @{ @"port": @(_tcpSocket.localPort).stringValue,
@"address": _tcpSocket.localHost ?: @"unknown",
@"family": _tcpSocket.isIPv6?@"IPv6":@"IPv4" };
}
}
return @{ @"port": @"0",
@"address": @"unknown",
@"family": @"unkown" };
}
- (BOOL)listen:(NSString *)host port:(int)port error:(NSError **)error
{
if (_tcpSocket) {

View File

@ -103,7 +103,7 @@ RCT_EXPORT_METHOD(listen:(nonnull NSNumber*)cId
- (void)onConnect:(TcpSocketClient*) client
{
[self.bridge.eventDispatcher sendDeviceEventWithName:[NSString stringWithFormat:@"tcp-%@-event", client.id]
body:@{ @"event": @"connect" }];
body:@{ @"event": @"connect", @"data": [client getAddress] }];
}
- (void)onData:(NSNumber *)clientID data:(NSData *)data
@ -127,9 +127,9 @@ RCT_EXPORT_METHOD(listen:(nonnull NSNumber*)cId
}
- (void)onError:(TcpSocketClient*) client withError:(NSError *)err {
NSString* msg = [[err userInfo] valueForKey:@"NSLocalizedFailureReason"];
NSString *msg = [err userInfo][@"NSLocalizedFailureReason"] ?: [err userInfo][@"NSLocalizedDescription"];
[self.bridge.eventDispatcher sendDeviceEventWithName:[NSString stringWithFormat:@"tcp-%@-event", client.id]
body:@{ @"event": @"error", @"data": @[msg] }];
body:@{ @"event": @"error", @"data": msg }];
}

View File

@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'react-native-tcp'
s.version = '0.0.3'
s.version = '0.1.3'
s.summary = 'node\'s net API in React Native.'
s.description = <<-DESC
Enables accessing tcp sockets in React Native.