如何重新连接okhttp-ws

How to reconnect okhttp-ws

如果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: Unable to start service ... (has extras) }: java.util.concurrent.RejectedExecutionException: Task okhttp3.RealCall$AsyncCall@3f946389 rejected from java.util.concurrent.ThreadPoolExecutor@d784f8e[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 1] at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3320)

看例子和我的简单方法library

...
try{
WebsocketClient.dispatcher().cancelAll();// to cancel all requests
}...

触发失败 ( ... ) 您可以重新连接

   /**
     * Configure this client to retry or not when a connectivity problem is encountered. By default,
     * this client silently recovers from the following problems:
     *
     * <ul>
     *   <li><strong>Unreachable IP addresses.</strong> If the URL's host has multiple IP addresses,
     *       failure to reach any individual IP address doesn't fail the overall request. This can
     *       increase availability of multi-homed services.
     *   <li><strong>Stale pooled connections.</strong> The {@link ConnectionPool} reuses sockets
     *       to decrease request latency, but these connections will occasionally time out.
     *   <li><strong>Unreachable proxy servers.</strong> A {@link ProxySelector} can be used to
     *       attempt multiple proxy servers in sequence, eventually falling back to a direct
     *       connection.
     * </ul>
     *
     * Set this to false to avoid retrying requests when doing so is destructive. In this case the
     * calling application should do its own recovery of connectivity failures.
     */
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.retryOnConnectionFailure(true);