【发布时间】:2018-11-14 13:16:22
【问题描述】:
我是一名安卓开发者。我正在为 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();
}
....
【问题讨论】:
标签: java android websocket java-websocket