|
@@ -30,6 +30,7 @@ class NettyClient{
|
|
|
/*伴生对象*/
|
|
|
companion object {
|
|
|
var instance = NettyClient()
|
|
|
+ var isConnecting = false
|
|
|
}
|
|
|
|
|
|
private lateinit var group: NioEventLoopGroup
|
|
@@ -54,8 +55,10 @@ class NettyClient{
|
|
|
}
|
|
|
|
|
|
/*连接*/
|
|
|
+ @Synchronized
|
|
|
fun connect(ip: String, port: Int, heartBeatSeconds: Long): Observable<Boolean> {
|
|
|
Log.d(TAG, "开始连接 " + ip + ":" + port +","+heartBeatSeconds)
|
|
|
+ isConnecting = true
|
|
|
|
|
|
this.ip = ip
|
|
|
this.port = port
|
|
@@ -99,10 +102,13 @@ class NettyClient{
|
|
|
it.onNext(false)
|
|
|
} else {
|
|
|
group.schedule(Runnable {
|
|
|
- reConnect()
|
|
|
+ group.shutdownGracefully()
|
|
|
+ connect(ip, port, heartBeatSeconds)
|
|
|
retryTimes++
|
|
|
}, retrySeconds * retryTimes, TimeUnit.SECONDS)
|
|
|
}
|
|
|
+ } finally {
|
|
|
+ isConnecting = false
|
|
|
}
|
|
|
}.compose(ThreadFromUtils.defaultSchedulers())
|
|
|
}
|
|
@@ -110,7 +116,7 @@ class NettyClient{
|
|
|
|
|
|
/*发送命令*/
|
|
|
fun sendMsg(msg: String): Observable<Boolean> {
|
|
|
-
|
|
|
+ Log.d(TAG, "TCP.发送消息:$msg")
|
|
|
return Observable.create<Boolean> { emitter ->
|
|
|
if (isConnect) {
|
|
|
channel?.writeAndFlush(msg)?.addListener {
|
|
@@ -129,14 +135,37 @@ class NettyClient{
|
|
|
|
|
|
/*重连*/
|
|
|
fun reConnect(): Observable<Boolean> {
|
|
|
- disConnect()
|
|
|
- return connect(ip, port, heartBeatSeconds)
|
|
|
+ if (isConnecting){
|
|
|
+ Log.w(TAG, "TCP.在连接过程中")
|
|
|
+ return Observable.create<Boolean>{
|
|
|
+ it.onNext(false)
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ isConnecting = true
|
|
|
+ return Observable.create<Boolean> {
|
|
|
+ try {
|
|
|
+ channel = bootstrap.connect().sync().channel();
|
|
|
+ it.onNext(channel!!.isActive)
|
|
|
+ isConnect = channel!!.isActive
|
|
|
+ } catch (e:Exception){
|
|
|
+ isConnect = false
|
|
|
+ it.onNext(false)
|
|
|
+ } finally {
|
|
|
+ isConnecting = false
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+// disConnect()
|
|
|
+// return connect(ip, port, heartBeatSeconds)
|
|
|
}
|
|
|
|
|
|
|
|
|
/*关闭连接*/
|
|
|
private fun disConnect() {
|
|
|
- isConnect = false
|
|
|
- group.shutdownGracefully()
|
|
|
+ if (channel!=null) {
|
|
|
+ isConnect = false
|
|
|
+ group.shutdownGracefully()
|
|
|
+ }
|
|
|
}
|
|
|
}
|