如果IP地址发生变化或连接失败,如何正确重新连接?
我试着重新连接okhttp-ws
.....
@Override
public void onFailure(IOException e, okhttp3.Response response) {
try {
connecting();
} catch (Exception e1) {
Timber.e(e1, "onFailure");
}
}
@Override
public void onClose(int code, String reason) {
Timber.d("Connection unexpectedly closed");
connecting();
}
public void connecting() {
if (wsClient == null) {
wsClient = builder.build();
if (call != null) call.cancel();
call = WebSocketCall.create(wsClient, request);
try {
lock.lockInterruptibly();
try { call.enqueue(listener);
} finally {
lock.unlock();
}
} catch (InterruptedException e) {
Timber.e(e, "connecting error");
}
}
我收到错误
java.lang.RuntimeException:无法启动服务...(有 extras)}:java.util.concurrent.RejectedExecutionException:Task okhttp3.RealCall$AsyncCall@3f946389拒绝了 java.util.concurrent.ThreadPoolExecutor@d784f8e [终止,池大小 = 0,活动线程= 0,排队任务= 0,已完成任务= 1] 在 android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3320)
答案 0 :(得分:4)
请参阅示例和我的简单library
...
try{
WebsocketClient.dispatcher().cancelAll();// to cancel all requests
}...
触发On Failed(...)您可以重新连接
答案 1 :(得分:4)
/ ** *配置此客户端是否在遇到连接问题时重试。默认情况下, *此客户端默默地从以下问题中恢复: * *
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.retryOnConnectionFailure(true);