troyzhxu / okhttps

如艺术一般优雅,像 1、2、3 一样简单,前后端通用,轻量却强大的 HTTP 客户端(同时支持 WebSocket 与 Stomp 协议)
https://ok.zhxu.cn
Apache License 2.0
487 stars 75 forks source link

WHttpTask onFailure 非能重置webSocket连接中状态 #47

Closed zpupup closed 2 years ago

zpupup commented 2 years ago

Describe the bug STOMP 重连时, 服务器关闭状态下在次调用stomp.connect()时, WebSocket status 任然是 STATUS_CONNECTING. 主要原因在WHttpTask.onFailure中未能重置WebSocket状态

To Reproduce Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior A clear and concise description of what you expected to happen.

Screenshots If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

Smartphone (please complete the following information):

Additional context Add any other context about the problem here.

troyzhxu commented 2 years ago

是在 Stomp 的 Disconnected 回调里再次调用 connect 方法吗?

zpupup commented 2 years ago

在 OnException 中

troyzhxu commented 2 years ago

OnException 里重连需要视情况判断一下,示例:

// Stomp 实例
Stomp stomp = Stomp.over(OkHttps.webSocket("/ws"));
// 用一个状态来记录是否连接成功过
AtomicInteger status = new AtomicInteger(0);

/**
 * 自定义的连接方法
 **/
public void connect() {
    status.set(0);       // 刚开始,状态置 0
    stomp.setOnConnected(s -> {
    status.set(1);   // 连接上,状态置 1 
    })
    .setOnException(exp -> {
    if (status.get() == 0) {
        connect();   // 如果没有成功连接过,则直接重连
    }
    })
    .setOnDisconnected(close -> {
    connect();      // 连接成功后又断开,则在这里进行重连
    })
    .connect();         // 真正发起连接
}