Andrey
Andrey

Reputation: 53

How to reconnect okhttp-ws

How to make right reconnect if ip address changed or fail connection?

I`m try make reconnect 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");
    }
}

and I receive an 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)

Upvotes: 5

Views: 8189

Answers (2)

drummor
drummor

Reputation: 51

   /**
     * 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);

Upvotes: 4

Andrey
Andrey

Reputation: 66

see exemple and my easy library

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

triggered On Failed ( ... ) you can reconnect

Upvotes: 5

Related Questions