我是一名 Android 开发人员。我正在使用 TakahikoKawasaki/nv-websocket-client 库作为 websocket 客户端。
它工作得很好。但是当我重新启动互联网连接或连接到 wifi 时,它不起作用。为了再次工作,我重新启动应用程序。
我尝试重新连接或重新创建,但没有任何帮助。
应用程序.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();
}
....
最佳答案
看看重新连接部分 here 。
你可能应该使用这个:
ws = ws.recreate().connect();
关于java - 互联网连接重新启动时 Websocket 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53301142/