我是一名Android开发人员。我正在为websocket客户端使用TakahikoKawasaki / nv-websocket-client库。
它工作得很好。但是,当我重新启动互联网连接或连接到wifi时,它无法正常工作。为了再次工作,我重启应用程序
我试图重新连接或重新创建,但没有任何帮助。
app.Java
public class App extends Application {
private static WebSocket ws = null;
WebSocketFactory factory = new WebSocketFactory().setConnectionTimeout(5000);
@Override
public void onCreate() {
super.onCreate();
try {
ws = factory.createSocket("wss://websocket/");
ws.connectAsynchronously();
} catch (Exception ignored) {
}
}
public WebSocket getSocket(){
try {
if(!ws.isOpen())
ws = ws.recreate();
} catch (IOException ignored) {
}
return ws;
}
}
main activity.Java
....
app.getSocket().addListener(getMessage);
String message;
try {
JSONObject json = new JSONObject();
json.put("class", "userIdFromUser");
JSONObject data = new JSONObject();
data.put("message", userInfoSharedP.getUserId());
data.put("senderId", userInfoSharedP.getUserId());
json.put("data",data);
message = json.toString();
app.getSocket().sendText(message);
} catch (JSONException | IOException e) {
e.printStackTrace();
}
....
看看部分Reconnection here。你可能应该使用这个:ws = ws.recreate().connect();