Android Socket.io Websocket Transport does not works in SSL

前端 未结 3 1792
予麋鹿
予麋鹿 2020-12-19 21:00

I\'m using gottox socket.io java client for an Android chat application.
I could connect to both web-socket and Xhr transport in HTTP mode. But when i switch to HTTPS o

3条回答
  •  甜味超标
    2020-12-19 21:42

    Update

    It might be that with new versions IO.setDefaultSSLContext and IO. setDefaultHostnameVerifier methods are not available. Instead now we can create our own OkHttpClient and set the hostname verifier and ssl socket factory etc on it as mentioned on socket.io-client-java usage. Here is the sniplet from there:

    OkHttpClient okHttpClient = new OkHttpClient.Builder()
                          .hostnameVerifier(myHostnameVerifier)
                          .sslSocketFactory(mySSLContext.getSocketFactory(), myX509TrustManager)
                          .build(); // default settings for all sockets 
    
    IO.setDefaultOkHttpWebSocketFactory(okHttpClient); 
    IO.setDefaultOkHttpCallFactory(okHttpClient);
    

    Initial Answer:

    I had the same issue with io.socket:socket.io-client:0.7.0 version of socket.io library on Android for long. It used to work fine for http protocol, however for https protocol it had trouble establishing connection giving xhr poll errors.

    Following solution works for me without modifying the library itself:

    // Socket connection
    private Socket mSocket;
    
    // Configure options
    IO.Options options = new IO.Options();
    // ... add more options
    
    // End point https 
    String yourEndpoint = "https://whatever.yoururl.com"
    String yourHostName = "yoururl.com"
    
    // If https, explicitly tell set the sslContext.
    if (yourEndpoint.startsWith("https://")) {        
        try {
            // Default settings for all sockets
    
            // Set default ssl context
            IO.setDefaultSSLContext(SSLContext.getDefault());
    
            // Set default hostname
            HostnameVerifier hostnameVerifier = new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
                    return hv.verify(yourHostName, session);
                }
            };
            IO.setDefaultHostnameVerifier(hostnameVerifier);
    
            // set as an option
            options.sslContext = SSLContext.getDefault();
            options.hostnameVerifier = hostnameVerifier;
            options.secure = true;
    
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
    
    // Instantiate the socket
    mSocket = IO.socket(mEndpoint, options);
    

    Hope this helps.

提交回复
热议问题