Skip to content

Commit b8f0458

Browse files
优化TcpClient,解决频繁重连会崩溃的问题
1 parent eeec635 commit b8f0458

File tree

2 files changed

+8
-8
lines changed

2 files changed

+8
-8
lines changed

app/src/main/java/com/pengxh/androidx/lib/view/MainActivity.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ public class MainActivity extends AndroidxBaseActivity<ActivityMainBinding> impl
3434

3535
private static final String TAG = "MainActivity";
3636
private final Context context = this;
37-
private final TcpClient tcpClient = new TcpClient("192.168.161.200", 3000, this);
37+
private final TcpClient tcpClient = new TcpClient(this);
3838

3939
@Override
4040
protected void setupTopBarLayout() {
@@ -49,7 +49,7 @@ public void onClick(View v) {
4949
if (tcpClient.isRunning()) {
5050
tcpClient.stop();
5151
} else {
52-
tcpClient.start();
52+
tcpClient.start("192.168.161.200", 3000);
5353
}
5454
}
5555
});

lite/src/main/java/com/pengxh/androidx/lite/utils/socket/tcp/TcpClient.java

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,16 +27,14 @@ public class TcpClient {
2727
private static final long RECONNECT_DELAY = 5L;
2828
private final Bootstrap bootStrap = new Bootstrap();
2929
private final NioEventLoopGroup loopGroup = new NioEventLoopGroup();
30-
private final String host;
31-
private final int port;
3230
private final OnTcpConnectStateListener listener;
31+
private String host;
32+
private int port;
3333
private Channel channel;
3434
private boolean isRunning = false;
3535
private int retryTimes = 0;
3636

37-
public TcpClient(String host, int port, OnTcpConnectStateListener listener) {
38-
this.host = host;
39-
this.port = port;
37+
public TcpClient(OnTcpConnectStateListener listener) {
4038
this.listener = listener;
4139
bootStrap.group(loopGroup)
4240
.channel(NioSocketChannel.class)
@@ -54,7 +52,9 @@ public boolean isRunning() {
5452
return isRunning;
5553
}
5654

57-
public void start() {
55+
public void start(String host, int port) {
56+
this.host = host;
57+
this.port = port;
5858
if (isRunning) {
5959
return;
6060
}

0 commit comments

Comments
 (0)