【问题标题】:Websocket not working when internet connection restart互联网连接重新启动时Websocket无法正常工作
【发布时间】: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


    【解决方案1】:

    查看部分重新连接here。 你可能应该使用这个: ws = ws.recreate().connect();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多