【问题标题】:How to reconnect okhttp-ws如何重新连接okhttp-ws
【发布时间】:2021-10-11 04:21:54
【问题描述】:

如果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: 无法启动服务...(有 额外)}:java.util.concurrent.RejectedExecutionException:任务 okhttp3.RealCall$AsyncCall@3f946389 被拒绝 java.util.concurrent.ThreadPoolExecutor@d784f8e[终止,池大小 = 0,活动线程 = 0,排队任务 = 0,已完成任务 = 1] 在 android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3320)

【问题讨论】:

    标签: java android okhttp


    【解决方案1】:

    看例子和我的简单library

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

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

    【讨论】:

      【解决方案2】:
         /**
           * 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);
      

      【讨论】:

      • 我试过这个用于网络套接字,不幸的是它没有重新连接网络套接字
      猜你喜欢
      • 1970-01-01
      • 2016-10-24
      • 1970-01-01
      • 2019-03-11
      • 1970-01-01
      • 2020-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多