refactor android, remove useless callbacks

This commit is contained in:
Andy Prock 2015-12-31 11:02:57 -08:00
parent ab0e3d91c5
commit 6a56aedebf
13 changed files with 113 additions and 107 deletions

View File

@ -162,9 +162,9 @@ TcpSocket.prototype.end = function(data, encoding) {
} }
this._destroyed = true; this._destroyed = true;
this._debug('closing'); this._debug('ending');
Sockets.end(this._id, this._debug.bind(this, 'end')); Sockets.end(this._id);
}; };
TcpSocket.prototype.destroy = function() { TcpSocket.prototype.destroy = function() {
@ -172,7 +172,7 @@ TcpSocket.prototype.destroy = function() {
this._destroyed = true; this._destroyed = true;
this._debug('destroying'); this._debug('destroying');
Sockets.destroy(this._id, this._debug.bind(this, 'destroy')); Sockets.destroy(this._id);
} }
}; };

View File

@ -1,3 +1,5 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript { buildscript {
repositories { repositories {
jcenter() jcenter()
@ -5,40 +7,14 @@ buildscript {
dependencies { dependencies {
classpath 'com.android.tools.build:gradle:1.3.1' classpath 'com.android.tools.build:gradle:1.3.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
} }
} }
apply plugin: 'com.android.library' allprojects {
repositories {
android { jcenter()
compileSdkVersion 23
buildToolsVersion "23.0.1"
defaultConfig {
minSdkVersion 16
targetSdkVersion 22
versionCode 1
versionName "0.2.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
// needed for https://github.com/square/okio/issues/58
lintOptions {
warning 'InvalidPackage'
} }
} }
repositories {
mavenCentral()
}
dependencies {
compile 'com.facebook.react:react-native:0.17.+'
compile 'com.koushikdutta.async:androidasync:2.1.6'
}

30
android/core/build.gradle Normal file
View File

@ -0,0 +1,30 @@
apply plugin: 'com.android.library'
android {
compileSdkVersion 23
buildToolsVersion "23.0.1"
defaultConfig {
minSdkVersion 16
targetSdkVersion 22
versionCode 1
versionName "0.2.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
// needed for https://github.com/square/okio/issues/58
lintOptions {
warning 'InvalidPackage'
}
}
dependencies {
compile 'com.facebook.react:react-native:0.17.+'
compile 'com.koushikdutta.async:androidasync:2.1.6'
}

17
android/core/proguard-rules.pro vendored Normal file
View File

@ -0,0 +1,17 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

View File

@ -2,6 +2,4 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.peel.react" > package="com.peel.react" >
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
</manifest> </manifest>

View File

@ -22,33 +22,25 @@ import java.net.UnknownHostException;
/** /**
* Created by aprock on 12/29/15. * Created by aprock on 12/29/15.
*/ */
public class TcpSocketManager { public final class TcpSocketManager {
private SparseArray<Object> mClients = new SparseArray<Object>(); private SparseArray<Object> mClients = new SparseArray<Object>();
private WeakReference<TcpSocketListener> listener; private WeakReference<TcpSocketListener> mListener;
private AsyncServer server = AsyncServer.getDefault(); private AsyncServer mServer = AsyncServer.getDefault();
private int instances = 5000; private int mInstances = 5000;
public TcpSocketManager(TcpSocketListener listener) throws IOException { public TcpSocketManager(TcpSocketListener listener) throws IOException {
this.listener = new WeakReference<TcpSocketListener>(listener); mListener = new WeakReference<TcpSocketListener>(listener);
}
private TcpSocketListener getListener() {
if (listener != null) {
return listener.get();
}
return null;
} }
private void setSocketCallbacks(final Integer cId, final AsyncSocket socket) { private void setSocketCallbacks(final Integer cId, final AsyncSocket socket) {
socket.setClosedCallback(new CompletedCallback() { socket.setClosedCallback(new CompletedCallback() {
@Override @Override
public void onCompleted(Exception ex) { public void onCompleted(Exception ex) {
TcpSocketListener listener = getListener(); TcpSocketListener listener = mListener.get();
if (listener != null) { if (listener != null) {
listener.onClose(cId, null); listener.onClose(cId, ex==null?null:ex.getMessage());
} }
} }
}); });
@ -56,7 +48,7 @@ public class TcpSocketManager {
socket.setDataCallback(new DataCallback() { socket.setDataCallback(new DataCallback() {
@Override @Override
public void onDataAvailable(DataEmitter emitter, ByteBufferList bb) { public void onDataAvailable(DataEmitter emitter, ByteBufferList bb) {
TcpSocketListener listener = getListener(); TcpSocketListener listener = mListener.get();
if (listener != null) { if (listener != null) {
listener.onData(cId, bb.getAllByteArray()); listener.onData(cId, bb.getAllByteArray());
} }
@ -67,7 +59,7 @@ public class TcpSocketManager {
@Override @Override
public void onCompleted(Exception ex) { public void onCompleted(Exception ex) {
if (ex != null) { if (ex != null) {
TcpSocketListener listener = getListener(); TcpSocketListener listener = mListener.get();
if (listener != null) { if (listener != null) {
listener.onError(cId, ex.getMessage()); listener.onError(cId, ex.getMessage());
} }
@ -86,12 +78,12 @@ public class TcpSocketManager {
socketAddress = new InetSocketAddress(port); socketAddress = new InetSocketAddress(port);
} }
server.listen(InetAddress.getByName(host), port, new ListenCallback() { mServer.listen(InetAddress.getByName(host), port, new ListenCallback() {
@Override @Override
public void onListening(AsyncServerSocket socket) { public void onListening(AsyncServerSocket socket) {
mClients.put(cId, socket); mClients.put(cId, socket);
TcpSocketListener listener = getListener(); TcpSocketListener listener = mListener.get();
if (listener != null) { if (listener != null) {
listener.onConnect(cId, socketAddress); listener.onConnect(cId, socketAddress);
} }
@ -99,25 +91,25 @@ public class TcpSocketManager {
@Override @Override
public void onAccepted(AsyncSocket socket) { public void onAccepted(AsyncSocket socket) {
setSocketCallbacks(instances, socket); setSocketCallbacks(mInstances, socket);
mClients.put(instances, socket); mClients.put(mInstances, socket);
TcpSocketListener listener = getListener(); TcpSocketListener listener = mListener.get();
if (listener != null) { if (listener != null) {
listener.onConnection(cId, instances, socketAddress); listener.onConnection(cId, mInstances, socketAddress);
} }
instances++; mInstances++;
} }
@Override @Override
public void onCompleted(Exception ex) { public void onCompleted(Exception ex) {
TcpSocketListener listener = getListener(); mClients.delete(cId);
TcpSocketListener listener = mListener.get();
if (listener != null) { if (listener != null) {
listener.onClose(cId, ex != null ? ex.getMessage() : null); listener.onClose(cId, ex != null ? ex.getMessage() : null);
} }
mClients.remove(cId);
} }
}); });
} }
@ -131,22 +123,19 @@ public class TcpSocketManager {
socketAddress = new InetSocketAddress(port); socketAddress = new InetSocketAddress(port);
} }
server.connectSocket(socketAddress, new ConnectCallback() { mServer.connectSocket(socketAddress, new ConnectCallback() {
@Override @Override
public void onConnectCompleted(Exception ex, AsyncSocket socket) { public void onConnectCompleted(Exception ex, AsyncSocket socket) {
if (ex != null) { TcpSocketListener listener = mListener.get();
TcpSocketListener listener = getListener(); if (ex == null) {
if (listener != null) {
listener.onError(cId, ex.getMessage());
}
} else {
mClients.put(cId, socket); mClients.put(cId, socket);
setSocketCallbacks(cId, socket); setSocketCallbacks(cId, socket);
TcpSocketListener listener = getListener();
if (listener != null) { if (listener != null) {
listener.onConnect(cId, socketAddress); listener.onConnect(cId, socketAddress);
} }
} else if (listener != null) {
listener.onError(cId, ex.getMessage());
} }
} }
}); });
@ -161,14 +150,17 @@ public class TcpSocketManager {
public void close(final Integer cId) { public void close(final Integer cId) {
Object socket = mClients.get(cId); Object socket = mClients.get(cId);
if (socket == null) { if (socket != null) {
return; if (socket instanceof AsyncSocket) {
} ((AsyncSocket) socket).close();
} else if (socket instanceof AsyncServerSocket) {
if (socket instanceof AsyncSocket) { ((AsyncServerSocket) socket).stop();
((AsyncSocket) socket).close(); }
} else if (socket instanceof AsyncServerSocket) { } else {
((AsyncServerSocket) socket).stop(); TcpSocketListener listener = mListener.get();
if (listener != null) {
listener.onError(cId, "unable to find socket");
}
} }
} }
@ -177,4 +169,5 @@ public class TcpSocketManager {
close(mClients.keyAt(i)); close(mClients.keyAt(i));
} }
mClients.clear(); mClients.clear();
}} }
}

View File

@ -124,7 +124,7 @@ public final class TcpSockets extends ReactContextBaseJavaModule implements TcpS
} }
@ReactMethod @ReactMethod
public void end(final Integer cId, final Callback callback) { public void end(final Integer cId) {
new GuardedAsyncTask<Void, Void>(getReactApplicationContext()) { new GuardedAsyncTask<Void, Void>(getReactApplicationContext()) {
@Override @Override
protected void doInBackgroundGuarded(Void... params) { protected void doInBackgroundGuarded(Void... params) {
@ -134,8 +134,8 @@ public final class TcpSockets extends ReactContextBaseJavaModule implements TcpS
} }
@ReactMethod @ReactMethod
public void destroy(final Integer cId, final Callback callback) { public void destroy(final Integer cId) {
end(cId, callback); end(cId);
} }
/** TcpSocketListener */ /** TcpSocketListener */

0
android/gradlew vendored Normal file → Executable file
View File

1
android/settings.gradle Normal file
View File

@ -0,0 +1 @@
include ':core'

View File

@ -2,4 +2,4 @@ rootProject.name = 'rctsockets'
include ':app' include ':app'
include ':react-native-tcp' include ':react-native-tcp'
project(':react-native-tcp').projectDir = new File(settingsDir, '../node_modules/react-native-tcp/android') project(':react-native-tcp').projectDir = new File(settingsDir, '../node_modules/react-native-tcp/android/core')

View File

@ -27,7 +27,7 @@ RCT_EXPORT_MODULE()
-(void)dealloc -(void)dealloc
{ {
for (NSNumber *cId in _clients.allKeys) { for (NSNumber *cId in _clients.allKeys) {
[self destroyClient:cId callback:nil]; [self destroyClient:cId];
} }
} }
@ -73,7 +73,7 @@ RCT_EXPORT_METHOD(connect:(nonnull NSNumber*)cId
RCT_EXPORT_METHOD(write:(nonnull NSNumber*)cId RCT_EXPORT_METHOD(write:(nonnull NSNumber*)cId
string:(NSString *)base64String string:(NSString *)base64String
callback:(RCTResponseSenderBlock)callback) { callback:(RCTResponseSenderBlock)callback) {
TcpSocketClient* client = [self findClient:cId callback:callback]; TcpSocketClient* client = [self findClient:cId];
if (!client) return; if (!client) return;
// iOS7+ // iOS7+
@ -82,14 +82,12 @@ RCT_EXPORT_METHOD(write:(nonnull NSNumber*)cId
[client writeData:data callback:callback]; [client writeData:data callback:callback];
} }
RCT_EXPORT_METHOD(end:(nonnull NSNumber*)cId RCT_EXPORT_METHOD(end:(nonnull NSNumber*)cId) {
callback:(RCTResponseSenderBlock)callback) { [self endClient:cId];
[self endClient:cId callback:callback];
} }
RCT_EXPORT_METHOD(destroy:(nonnull NSNumber*)cId RCT_EXPORT_METHOD(destroy:(nonnull NSNumber*)cId) {
callback:(RCTResponseSenderBlock)callback) { [self destroyClient:cId];
[self destroyClient:cId callback:callback];
} }
RCT_EXPORT_METHOD(listen:(nonnull NSNumber*)cId RCT_EXPORT_METHOD(listen:(nonnull NSNumber*)cId
@ -143,22 +141,19 @@ RCT_EXPORT_METHOD(listen:(nonnull NSNumber*)cId
} }
- (void)onError:(TcpSocketClient*) client withError:(NSError *)err { - (void)onError:(TcpSocketClient*) client withError:(NSError *)err {
NSString *msg = [err userInfo][@"NSLocalizedFailureReason"] ?: [err userInfo][@"NSLocalizedDescription"]; NSString *msg = err.localizedFailureReason ?: err.localizedDescription;
[self.bridge.eventDispatcher sendDeviceEventWithName:[NSString stringWithFormat:@"tcp-%@-error", client.id] [self.bridge.eventDispatcher sendDeviceEventWithName:[NSString stringWithFormat:@"tcp-%@-error", client.id]
body:msg]; body:msg];
} }
-(TcpSocketClient*)findClient:(nonnull NSNumber*)cId callback:(RCTResponseSenderBlock)callback -(TcpSocketClient*)findClient:(nonnull NSNumber*)cId
{ {
TcpSocketClient *client = _clients[cId]; TcpSocketClient *client = _clients[cId];
if (!client) { if (!client) {
if (!callback) { NSString *msg = [NSString stringWithFormat:@"no client found with id %@", cId];
RCTLogError(@"%@.missing callback parameter.", [self class]); [self.bridge.eventDispatcher sendDeviceEventWithName:[NSString stringWithFormat:@"tcp-%@-error", cId]
} else { body:msg];
callback(@[[NSString stringWithFormat:@"no client found with id %@", cId]]);
}
return nil; return nil;
} }
@ -166,20 +161,16 @@ RCT_EXPORT_METHOD(listen:(nonnull NSNumber*)cId
} }
-(void)endClient:(nonnull NSNumber*)cId -(void)endClient:(nonnull NSNumber*)cId
callback:(RCTResponseSenderBlock)callback
{ {
TcpSocketClient* client = [self findClient:cId callback:callback]; TcpSocketClient* client = [self findClient:cId];
if (!client) return; if (!client) return;
[client end]; [client end];
if (callback) callback(@[]);
} }
-(void)destroyClient:(nonnull NSNumber*)cId -(void)destroyClient:(nonnull NSNumber*)cId
callback:(RCTResponseSenderBlock)callback
{ {
TcpSocketClient* client = [self findClient:cId callback:nil]; TcpSocketClient* client = [self findClient:cId];
if (!client) return; if (!client) return;
[client destroy]; [client destroy];