首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >当internet断开时重新连接OkHttp websocket

当internet断开时重新连接OkHttp websocket
EN

Stack Overflow用户
提问于 2019-01-08 16:40:05
回答 2查看 5K关注 0票数 12

我有下面的课程。我正在尝试重新连接WebSocket,以防出现故障

代码语言:javascript
运行
复制
public class WebSocketClient extends WebSocketListener {
    volatile OkHttpClient client;
    volatile WebSocket webSocket;
    volatile Boolean isConnected = false;

    public WebSocketClient() {
        Proxy proxy = null;

        if (Main.useProxy) {
            tinder.CustomProxy proxyCustom = ProxyManager.GetStaticProxy(ThreadLocalManager.account.get().getProxyId());
            proxy = new Proxy(Proxy.Type.HTTP,
                    new InetSocketAddress(proxyCustom.getProxyIp(), proxyCustom.getProxyPort()));
        }

        client = new OkHttpClient.Builder().proxy(proxy).readTimeout(2, TimeUnit.SECONDS)
                .connectTimeout(2, TimeUnit.SECONDS).build();


        Request request = new Request.Builder().url("wss://echo.com/ws")
                .addHeader("Accept-Language", "en").build();
        webSocket = client.newWebSocket(request, this);
    }

    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        AnsiConsole.out.println(Ansi.ansi().fg(Ansi.Color.GREEN).a("Socket connection successful").reset());
        isConnected = true;
    }

    @Override
    public void onMessage(WebSocket webSocket, String text) {
        System.out.println("Text MESSAGE: " + text);
    }

    @Override
    public void onMessage(WebSocket webSocket, ByteString bytes) {

    }

    @Override
    public void onClosing(WebSocket webSocket, int code, String reason) {
        webSocket.close(1000, null);
        System.out.println("CLOSE: " + code + " " + reason);
        isConnected = false;
    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        isConnected = false;
        AnsiConsole.out
                .println(Ansi.ansi().fg(Ansi.Color.RED).a("Socket connection failed! will try to reconnect").reset());

        while (!isConnected) {
            try {
                AnsiConsole.out
                        .println(Ansi.ansi().fg(Ansi.Color.YELLOW).a("Waiting to try socket connection!").reset());
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            Request request = new Request.Builder().url("wss://echo.com/ws")
                    .addHeader("Accept-Language", "en").build();
            webSocket = client.newWebSocket(request, this);
        }

        if (isConnected) {
            AnsiConsole.out.println(Ansi.ansi().fg(Ansi.Color.GREEN).a("Socket connection successful").reset());
        }
    }

    public void close() {
        if (webSocket != null) {
            webSocket.close(1000, "Connection closed");
        }
        client.dispatcher().executorService().shutdown();
    }

}

问题是,如果需要多次尝试重新连接,那么onFailure方法将被多次调用。导致多个web套接字连接而不是一个。

当websocket断开时,如何重新连接单次连接?

EN

回答 2

Stack Overflow用户

发布于 2019-03-02 17:31:06

对于多个空闲连接客户端,提供connectionPool

代码语言:javascript
运行
复制
client.connectionPool().evictAll();

evictAll()方法将清除所有连接。

票数 1
EN

Stack Overflow用户

发布于 2019-11-09 12:50:36

代码语言:javascript
运行
复制
public class WebSocketClient extends WebSocketListener {
    volatile OkHttpClient client;
    volatile WebSocket webSocket;
    volatile Boolean isConnected = false;

    public WebSocketClient() {
        Proxy proxy = null;

        if (Main.useProxy) {
            tinder.CustomProxy proxyCustom = ProxyManager.GetStaticProxy(ThreadLocalManager.account.get().getProxyId());
            proxy = new Proxy(Proxy.Type.HTTP,
                    new InetSocketAddress(proxyCustom.getProxyIp(), proxyCustom.getProxyPort()));
        }

        client = new OkHttpClient.Builder().proxy(proxy).readTimeout(2, TimeUnit.SECONDS)
                .connectTimeout(2, TimeUnit.SECONDS).build();

        Request request = new Request.Builder().url("wss://echo.com/ws")
                .addHeader("Accept-Language", "en").build();
        webSocket = client.newWebSocket(request, this);

        // First Change
        client.connectionPool.evictAll();
    }

    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        AnsiConsole.out.println(Ansi.ansi().fg(Ansi.Color.GREEN).a("Socket connection successful").reset());
        isConnected = true;
    }

    @Override
    public void onMessage(WebSocket webSocket, String text) {
        System.out.println("Text MESSAGE: " + text);
    }

    @Override
    public void onMessage(WebSocket webSocket, ByteString bytes) {

    }

    @Override
    public void onClosing(WebSocket webSocket, int code, String reason) {
        webSocket.close(1000, null);
        System.out.println("CLOSE: " + code + " " + reason);
        isConnected = false;
    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        // Second Change
        webSocket.close(1000, null);
        close();
        Thread.sleep(10000);

        Request request = new Request.Builder().url("wss://echo.com/ws")
                .addHeader("Accept-Language", "en").build();
        webSocket = client.newWebSocket(request, this);
    }

    public void close() {
        if (webSocket != null) {
            webSocket.close(1000, "Connection closed");
        }
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54088030

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档