我使用以下适用于Android的websocket库:
https://github.com/TakahikoKawasaki/nv-websocket-client
只要当前活动处于活动状态,我希望能够在断开连接时每隔5秒重新连接一次。这是我的逻辑。
@Override
public void onConnected(WebSocket websocket, Map<String, List<String>> headers) throws Exception {
Log.e(TAG, "connected");
mIsActivityAlive = true;
super.onConnected(websocket, headers);
}
@Override
public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) throws Exception {
super.onDisconnected(websocket, serverCloseFrame, clientCloseFrame, closedByServer);
Log.e(TAG, "disconnected");
if (mIsActivityAlive) {
while(!mWs.isOpen()) {
Thread.sleep(5 * 1000);
Log.e(TAG, "reconnecting");
connectWs();
}
}
}
public void connectWs() {
try {
mWs = new WebSocketFactory().setConnectionTimeout(5 * 1000).createSocket("MY_WS_URL");
mWs.addListener(wsAdapter);
mWs.connectAsynchronously();
} catch (IOException e) {
e.printStackTrace();
}
}
这种逻辑工作正常 - 但是,在重新连接后websocket连接后,它会继续尝试重新连接。我认为在while循环中使用!mWs.isOpen
可以解决这个问题。我在mWs.isOpen
回调中记录了onConnected
及其true
,但它仍然在false
回调中显示onDisconnected
。我觉得它与Thread.sleep
有关,但我不知道从哪里开始寻找。