Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using secure websockets (wss) with OkHttp

I have tried to use OkHttp3 for connecting to a secure websocket server. When using wss://echo.websocket.org it is working fine, no problem, but when connecting to a production server for an ongoing project I do not properly connect to it. After 30-40 seconds onClosing is called in WebSocketListener.

I suspect this has something to with SSL/TLS encryption in wss. Is there a way to let OkHttpClient accept new certificates?

This is the code I am using now to establish a websocket connection with OkHttp3.

WebSocket webSocket;
OkHttpClient client;

OkHttpClient.Builder builder = new OkHttpClient.Builder();
client = builder.build();
Request request = new Request.Builder()
        .url(MainActivity.WS_URL)
        .header("Auth-Token","secret-api-token-here")
        .build();
Log.i("WebSockets", "Headers: " + request.headers().toString());
webSocket = client.newWebSocket(request, new WebSocketListener() {

    private static final int NORMAL_CLOSURE_STATUS = 1000;
    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        webSocket.send("{Auth-Token:secret-api-token-here}");
        Log.i("WebSockets", "Connection accepted!");
        //webSocket.close(NORMAL_CLOSURE_STATUS, "Goodbye !");
    }
    @Override
    public void onMessage(WebSocket webSocket, String text) {
        Log.i("WebSockets", "Receiving : " + text);
    }
    @Override
    public void onMessage(WebSocket webSocket, ByteString bytes) {
        Log.i("WebSockets", "Receiving bytes : " + bytes.hex());
    }
    @Override
    public void onClosing(WebSocket webSocket, int code, String reason) {
        webSocket.close(NORMAL_CLOSURE_STATUS, null);
        Log.i("WebSockets", "Closing : " + code + " / " + reason);
    }
    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        Log.i("WebSockets", "Error : " + t.getMessage());
    }});
}
like image 898
user1736049 Avatar asked Nov 07 '22 15:11

user1736049


1 Answers

I used OkHttp3 websocket to connect with a server over encrypted connection wss and I face the same problem. Which later turned out that the server was closing the connection after certain period of time.

like image 74
Ali Yusuf Avatar answered Nov 14 '22 21:11

Ali Yusuf