我是一名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;
}
}
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();
}
....