WebSocket调用reconnectBlocking报 WebSocketClient objects are not reuseable

关于websocket重连的问题。首先先区分出来websocket的四种状态

public enum ReadyState {
    NOT_YET_CONNECTED, OPEN, CLOSING, CLOSED
}

网上一堆怎么连接的文章,这里不再赘述。说重点:

我之前的代码

if (mClient != null && !mClient.isOpen()) {
    new Thread(new Runnable() {
        @Override
        public void run() {
                try {
                    mClient.reconnectBlocking();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
    }).start();
}

直接重连,就会报WebSocketClient objects are not reuseable。

这个就对于websocket的四种状态没有进行区分,当重连的时候,没有排除之前没有连接上这种状态,导致这种状态代码会崩溃。正确的应该如下

if (mClient != null && !mClient.isOpen()) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            if (mClient.getReadyState().equals(ReadyState.NOT_YET_CONNECTED)){
                try {
                    mClient.connectBlocking();
                } catch (Exception e) {
                }
            }else if (mClient.getReadyState().equals(ReadyState.CLOSING) || mClient.getReadyState().equals(ReadyState.CLOSED)){
                try {
                    mClient.reconnectBlocking();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }).start();
}

希望能帮到你。(菜鸟选手,希望批评指正)

你可能感兴趣的:(WebSocket调用reconnectBlocking报 WebSocketClient objects are not reuseable)