美文网首页
Socket.IO android4.4 Connection

Socket.IO android4.4 Connection

作者: sindorina | 来源:发表于2019-03-08 11:09 被阅读0次

    1.我使用的是https://github.com/socketio/socket.io-client-java github开源的socket库
    2.代码如下

    private class MyHostnameVerifier implements HostnameVerifier {
    
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        }
        
        private class MyTrustManager implements X509TrustManager {
    
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    
            }
    
            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    
            }
    
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                //这里不能返回null 否则会报空指针错误
                X509Certificate[] x509Certificates = new X509Certificate[0];
                return x509Certificates;
            }
        }
    
    TrustManager[] trustAllCerts= new TrustManager[] { new X509TrustManager() {
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return new java.security.cert.X509Certificate[] {};
                    }
    
                    public void checkClientTrusted(X509Certificate[] chain,
                                                   String authType) throws CertificateException {
                    }
    
                    public void checkServerTrusted(X509Certificate[] chain,
                                                   String authType) throws CertificateException {
                    }
                } };
                SSLContext sc = SSLContext.getInstance("TLS");
                sc.init(null, trustAllCerts, new SecureRandom());
                Tls12SocketFactory socketFactory = new Tls12SocketFactory(sc.getSocketFactory());
                OkHttpClient okHttpClient = new OkHttpClient.Builder()
                        .hostnameVerifier(new MyHostnameVerifier())
                        .sslSocketFactory(socketFactory, new MyTrustManager())
                        .build();
    
                // default settings for all sockets
                IO.setDefaultOkHttpWebSocketFactory(okHttpClient);
                IO.setDefaultOkHttpCallFactory(okHttpClient);
    
                // set as an option
                IO.Options opts = new IO.Options();
                opts.callFactory = okHttpClient;
                opts.webSocketFactory = okHttpClient;
                Socket mSocket = IO.socket(SocketUri, opts);
    

    相关文章

      网友评论

          本文标题:Socket.IO android4.4 Connection

          本文链接:https://www.haomeiwen.com/subject/sjglpqtx.html