I am an android developer. I am using TakahikoKawasaki/nv-websocket-client library for websocket client.
It is working nice. But when I restart internet connection or connecting to wifi it is not working. For working again I restart application.
I tried to reconnect or recreate but nothing helps.
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;
}
}
MainActivity.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();
}
....
Have a look at part Reconnection here . You probably should use this: ws = ws.recreate().connect();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.