react-native-tcp/ios/TcpSocketClient.m

266 lines
7.5 KiB
Mathematica
Raw Normal View History

2015-12-23 18:56:33 +00:00
/**
* Copyright (c) 2015-present, Peel Technologies, Inc.
* All rights reserved.
*/
#import <netinet/in.h>
#import <arpa/inet.h>
#import "TcpSocketClient.h"
#import "RCTBridgeModule.h"
#import "GCDAsyncSocket.h"
2015-12-07 19:45:33 +00:00
NSString *const RCTTCPErrorDomain = @"RCTTCPErrorDomain";
@interface TcpSocketClient()
{
@private
GCDAsyncSocket *_tcpSocket;
2015-12-16 23:05:08 +00:00
NSMutableDictionary<NSNumber *, RCTResponseSenderBlock> *_pendingSends;
NSLock *_lock;
2015-12-15 00:16:45 +00:00
long _sendTag;
}
2015-12-22 23:53:08 +00:00
- (id)initWithClientId:(NSNumber *)clientID andConfig:(id<SocketClientDelegate>)aDelegate;
- (id)initWithClientId:(NSNumber *)clientID andConfig:(id<SocketClientDelegate>)aDelegate andSocket:(GCDAsyncSocket*)tcpSocket;
@end
@implementation TcpSocketClient
+ (id)socketClientWithId:(nonnull NSNumber *)clientID andConfig:(id<SocketClientDelegate>)delegate
{
2015-12-22 23:53:08 +00:00
return [[[self class] alloc] initWithClientId:clientID andConfig:delegate andSocket:nil];
}
2015-12-22 23:53:08 +00:00
- (id)initWithClientId:(NSNumber *)clientID andConfig:(id<SocketClientDelegate>)aDelegate
{
return [self initWithClientId:clientID andConfig:aDelegate andSocket:nil];
}
- (id)initWithClientId:(NSNumber *)clientID andConfig:(id<SocketClientDelegate>)aDelegate andSocket:(GCDAsyncSocket*)tcpSocket;
{
self = [super init];
if (self) {
_id = clientID;
_clientDelegate = aDelegate;
_pendingSends = [NSMutableDictionary dictionary];
_lock = [[NSLock alloc] init];
2015-12-22 23:53:08 +00:00
_tcpSocket = tcpSocket;
}
return self;
}
2015-12-15 00:16:45 +00:00
- (BOOL)connect:(NSString *)host port:(int)port withOptions:(NSDictionary *)options error:(NSError **)error
{
2015-12-15 00:16:45 +00:00
if (_tcpSocket) {
if (error) {
*error = [self badInvocationError:@"this client's socket is already connected"];
}
return false;
}
_tcpSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:[self methodQueue]];
2015-12-15 00:16:45 +00:00
BOOL result = false;
NSString *localAddress = (options?options[@"localAddress"]:nil);
NSNumber *localPort = (options?options[@"localPort"]:nil);
if (!localAddress && !localPort) {
result = [_tcpSocket connectToHost:host onPort:port error:error];
} else {
NSMutableArray *interface = [NSMutableArray arrayWithCapacity:2];
[interface addObject: localAddress?localAddress:@""];
if (localPort) {
[interface addObject:[localPort stringValue]];
}
result = [_tcpSocket connectToHost:host
onPort:port
viaInterface:[interface componentsJoinedByString:@":"]
withTimeout:-1
error:error];
}
return result;
}
2015-12-23 23:14:41 +00:00
- (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" };
}
2015-12-22 23:53:08 +00:00
- (BOOL)listen:(NSString *)host port:(int)port error:(NSError **)error
{
if (_tcpSocket) {
if (error) {
*error = [self badInvocationError:@"this client's socket is already connected"];
}
return false;
}
_tcpSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:[self methodQueue]];
BOOL result = [_tcpSocket acceptOnInterface:host port:port error:error];
if (result == YES) {
[_clientDelegate onConnect: self];
[_tcpSocket readDataWithTimeout:-1 tag:_id.longValue];
}
return result;
}
- (void)setPendingSend:(RCTResponseSenderBlock)callback forKey:(NSNumber *)key
{
[_lock lock];
@try {
[_pendingSends setObject:callback forKey:key];
}
@finally {
[_lock unlock];
}
}
- (RCTResponseSenderBlock)getPendingSend:(NSNumber *)key
{
[_lock lock];
@try {
return [_pendingSends objectForKey:key];
}
@finally {
[_lock unlock];
}
}
- (void)dropPendingSend:(NSNumber *)key
{
[_lock lock];
@try {
[_pendingSends removeObjectForKey:key];
}
@finally {
[_lock unlock];
}
}
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)msgTag
{
NSNumber* tagNum = [NSNumber numberWithLong:msgTag];
RCTResponseSenderBlock callback = [self getPendingSend:tagNum];
if (callback) {
callback(@[]);
[self dropPendingSend:tagNum];
}
}
- (void) writeData:(NSData *)data
callback:(RCTResponseSenderBlock)callback
{
2015-12-15 00:16:45 +00:00
[_tcpSocket writeData:data withTimeout:-1 tag:_sendTag];
if (callback) {
2015-12-22 23:53:08 +00:00
[self setPendingSend:callback forKey:@(_sendTag)];
}
2015-12-15 00:16:45 +00:00
_sendTag++;
2015-12-22 23:53:08 +00:00
[_tcpSocket readDataWithTimeout:-1 tag:_id.longValue];
}
2015-12-15 00:16:45 +00:00
- (void)end
{
[_tcpSocket disconnectAfterWriting];
}
2015-12-15 00:16:45 +00:00
- (void)destroy
{
[_tcpSocket disconnect];
}
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
if (!_clientDelegate) return;
2015-12-22 23:53:08 +00:00
[_clientDelegate onData:@(tag) data:data];
2015-12-15 00:16:45 +00:00
2015-12-22 23:53:08 +00:00
[sock readDataWithTimeout:-1 tag:tag];
}
- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket
{
TcpSocketClient *inComing = [[TcpSocketClient alloc] initWithClientId:[_clientDelegate generateRandomId]
andConfig:_clientDelegate
andSocket:newSocket];
[_clientDelegate onConnection: inComing
toClient: _id];
[newSocket readDataWithTimeout:-1 tag:inComing.id.longValue];
}
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
if (!_clientDelegate) return;
[_clientDelegate onConnect:self];
2015-12-22 23:53:08 +00:00
[sock readDataWithTimeout:-1 tag:_id.longValue];
}
2015-12-15 00:16:45 +00:00
- (void)socketDidCloseReadStream:(GCDAsyncSocket *)sock
{
2015-12-22 23:53:08 +00:00
// TODO : investigate for half-closed sockets
2015-12-24 19:18:51 +00:00
// for now close the stream completely
[sock disconnect];
2015-12-15 00:16:45 +00:00
}
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
if (!_clientDelegate) return;
2015-12-24 19:18:51 +00:00
[_clientDelegate onClose:self withError:(!err || err.code == GCDAsyncSocketClosedError ? nil : err)];
2015-12-15 00:16:45 +00:00
}
- (NSError *)badParamError:(NSString *)errMsg
{
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
2015-12-07 19:45:33 +00:00
return [NSError errorWithDomain:RCTTCPErrorDomain
code:RCTTCPBadParamError
userInfo:userInfo];
}
- (NSError *)badInvocationError:(NSString *)errMsg
{
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
2015-12-07 19:45:33 +00:00
return [NSError errorWithDomain:RCTTCPErrorDomain
code:RCTTCPInvalidInvocationError
userInfo:userInfo];
}
- (NSError *)sendFailedError:(NSString *)errMsg
{
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
2015-12-07 19:45:33 +00:00
return [NSError errorWithDomain:RCTTCPErrorDomain
code:RCTTCPSendFailedError
userInfo:userInfo];
}
- (dispatch_queue_t)methodQueue
{
return dispatch_get_main_queue();
}
@end