這幾天遇到一個需求---使用websock進行實時通信,並且保證長時間連接。
採取的方案是利用線程來定時進行webSocket重新連接(即斷開後重新連接)。這種方法覺得比較笨,但是這種方法比較有效。
1、定時連接線程,比較簡單的一個繼承Thread的類
public class ReconnectionWSThread extends Thread {
public volatile boolean isStop = false; //停止線程標記
@Override
public void run() {
super.run();
while (!isStop) {
try {
LogUtils.e("ReconnectionWSThread", " --- ReconnectionWSRThread 啓動 ");
Thread.sleep(10 * 60 * 1000);
//重連操作
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
2、錯誤重連線程
public class ReconnectionWSErrorThread extends Thread {
public volatile boolean isStop = false; //停止線程標記
@Override
public void run() {
super.run();
while (!isStop) {
try {
LogUtils.e("ReconnectionWSErrorThread", " --- ReconnectionWSErrorThread 啓動 ");
Thread.sleep(2 * 1000);
//重連操作
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
正常情況下的長連接線程(ReconnectionWSThread),在一個合適的位置開啓就可以,主要與錯誤重連(ReconnectionWSErrorThread)交替運行。
在okhttp上支持websocket通信:如果通信過程中出現錯誤或者連接斷開會回掉在onFailure方法中
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
super.onFailure(webSocket, t, response);
BaseApplication.isReconnect = true;//錯誤重連
BaseApplication.BaseReconnectionWSThread.isStop = true; //停止長連接線程
if (BaseApplication.isErrorReconnect) { //第一次進入onFailure回掉
BaseApplication.BaseReconnectionWSErrorThread.start(); //啓動錯誤重連
BaseApplication.isErrorReconnect = false;
} else {
if (!BaseApplication.BaseReconnectionWSErrorThread.isAlive()) { //判斷線程run方法是否還在運行中,注意當run方法運行結束後,相當於線程結束
BaseApplication.BaseReconnectionWSErrorThread = new ReconnectionWSErrorThread(); //啓動新的線程
BaseApplication.BaseReconnectionWSErrorThread.start();
}
}
}
在onMessage回掉中:
//錯誤重連
if (BaseApplication.isReconnect) {
BaseApplication.BaseReconnectionWSErrorThread.isStop = true;
BaseApplication.isReconnect = false;
BaseApplication.BaseReconnectionWSThread = new ReconnectionWSThread(); //重新啓動線程
BaseApplication.BaseReconnectionWSThread.start();
}
BaseApplition:
public class BaseApplication extends Application {
public static boolean isReconnect = false;
public static boolean isErrorReconnect = true;
public static ReconnectionWSThread BaseReconnectionWSThread;
public static ReconnectionWSErrorThread BaseReconnectionWSErrorThread;
@Override
public void onCreate() {
BaseReconnectionWSThread = new ReconnectionWSThread();
BaseReconnectionWSErrorThread = new ReconnectionWSErrorThread();
super.onCreate();
}
public static BaseRequest getBaseRequestInstance(){
return BaseRequestInstance;
}
}
附:如果有更好的方法歡迎討論指正,感謝感謝!!!