Socket.lo连接未设置

时间:2018-04-20 08:50:42

标签: android sockets

我想在我的Android应用程序中设置一个Socket.io连接,但它没有被设置。 沿着那个我想发送标题连接。 此代码始终显示连接超时错误

private static final String SOCKET_URI = "https://xxx.xxx.xxx";
private static final String[] TRANSPORTS = {
        "websocket"
};
    try {
        final IO.Options options = new IO.Options();
        options.transports = TRANSPORTS;
        options.reconnection = true;
        options.port = 5000;
        options.reconnectionAttempts = 10;
        options.reconnectionDelay = 100;
        options.forceNew = true;
        mSocket = IO.socket(SOCKET_URI, options);

        mSocket.on(Socket.EVENT_CONNECT,onConnect);
        mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);

        mSocket.io().on(Manager.EVENT_TRANSPORT, new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                Transport transport = (Transport) args[0];
                Log.e(TAG,"Transport Listener "+ args[0].hashCode());

                transport.on(Transport.EVENT_REQUEST_HEADERS, new Emitter.Listener() {
                    @Override
                    public void call(Object... args) {
                        @SuppressWarnings("unchecked")
                        Map<String, String> headers = (Map<String, String>) args[0];
                        headers.put("xxxxxxxx", "xxxxx);
                })
        });

        mSocket.connect();

    } catch (final URISyntaxException e) {
        Log.e(TAG, e.toString());
   }
}

1 个答案:

答案 0 :(得分:0)

你要点击的是https,所以你需要提供证书来连接到它。

将以下类添加到项目中:

public class SSLContextManager
{
    public static SSLContext getSSLContext(Context context) throws 
    KeyStoreException, CertificateException, NoSuchAlgorithmException, 
    IOException, KeyManagementException, NoSuchProviderException
{
    // Load CAs from an InputStream
    CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
    InputStream cert = context.getResources().openRawResource(R.raw.my_cert); // Place your 'my_cert.crt' file in `res/raw`
    Certificate ca;
    try
    {
        ca = cf.generateCertificate(cert);
    }
    finally
    {
        cert.close();
    }

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", ca);

    // Create a TrustManager that trusts the CAs in our KeyStore
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);

    // Create an SSLContext that uses our TrustManager
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, tmf.getTrustManagers(), null);

    return sslContext;
}

public static SSLContext getTrustAllSSLContext() throws NoSuchAlgorithmException, KeyManagementException
{
    // Create a trust manager that does not validate certificate chains
    final TrustManager[] trustAllCerts = new TrustManager[] {
            new X509TrustManager() {
                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                }

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType){
                }

                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return new java.security.cert.X509Certificate[]{};
                }
            }
    };

    // Install the all-trusting trust manager
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

    return sslContext;
}

}

之后添加以下行来定义选项:

options.setDefaultSSLContext(SSLContextManager.getSSLContext(context));

您还需要在您的uri中输入端口:

private static final String SOCKET_URI = "https://xxx.xxx.xxx:5000";

如果您想绕过ssl验证,请使用以下代码:

    options.setDefaultSSLContext(SSLContextManager.getTrustAllSSLContext());
            options.setDefaultHostnameVerifier(new HostnameVerifier()
            {
                @Override
                public boolean verify(String s, SSLSession sslSession)
                {
                    return true;
                }
            });