Skip to content

Unable to connect using https #26

Closed

Description

@anshulvij

/I am using node.js server side and android and another node.js client side web application.
The wep application is able to connect securely while the android application is just giving an timeout error.
/

//The code for creating sslcontext
Log.d(TAG,"setupContext");
//Using a client certificate
String password = "password"
KeyStore keyStore = KeyStore.getInstance("PKCS12");
InputStream is = context.getResources().openRawResource(R.raw.client_crt);
keyStore.load(is, password.toCharArray());
is.close();

    KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
    kmf.init(keyStore, password.toCharArray());
    KeyManager[] keyManagers = kmf.getKeyManagers();

    // Load CAs from an InputStream
    // (could be from a resource or ByteArrayInputStream or ...)
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    // Using self signed certificate
    is = context.getResources().openRawResource(R.raw.cacert);
    InputStream caInput = new BufferedInputStream(is);
    Certificate ca;
    ca = cf.generateCertificate(caInput);
    Log.i(TAG,"ca=" + ((X509Certificate) ca).getSubjectDN());
    caInput.close();


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

    // Create a TrustManager that trusts the CAs in our KeyStore
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
    tmf.init(trustStore);
    TrustManager[] trustManagers =  tmf.getTrustManagers();

    // Create an SSLContext that uses our TrustManager
    SSLContext sslcontext = SSLContext.getInstance("TLS");

    sslcontext.init(keyManagers, trustManagers, null);

    IO.Options opts = new IO.Options();
    opts.forceNew = true;
    opts.reconnection = false;
    opts.sslContext = mSslContext;
    opts.secure=true;
    mSocket = IO.socket("https://" + mIpAddress + ":" + mPort+"/", opts);
    mSocket.connect();
    mSocket.on(Socket.EVENT_CONNECT, mConnectionListener);
    mSocket.on(Socket.EVENT_DISCONNECT,mDisconnectionListener);
    mSocket.on(Socket.EVENT_ERROR,mErrorListener);
    mSocket.on(Socket.EVENT_MESSAGE,mMessageListener);
    mSocket.on(Socket.EVENT_CONNECT_ERROR,mConnectionErrorListener);

     // I never get call for EVENT_CONNECT

///////////////////////////SERVER CODE///////////////////////////////////////////////
var privateKey = fs.readFileSync('certificates/server.key').toString();
var certificate = fs.readFileSync('certificates/server.crt').toString();
var ca = fs.readFileSync('certificates/cacert.pem').toString();
// Sending and receiving events with Socket.IO
var app = express();
https.globalAgent.options.rejectUnauthorized = false;
var server = https.createServer({key:privateKey,cert:certificate,ca:ca },app);
// var server = require('http').Server(app);
exports.io = require('./sockets').listen(server);
//Server is listening on port 3000

Please tell a way to enable logs in android app for socket.io and possible cause of this problem.
There is no activity in node.js terminal as if the socket never got a call after using https it work fine if I use http
Thanks and regards,
Anshul

Activity

  1. nkzawa commented on Aug 4, 2014

    @nkzawa
    Contributor

    Umm, I'm not sure what the problem is, but it may be helpful to compare with my settings for unit tests.

    https://github.com/nkzawa/socket.io-client.java/blob/master/src/test/java/com/github/nkzawa/socketio/client/SSLConnectionTest.java#L51

    Set the log level FINE or lower to see all logs.

  2. mifoss commented on Oct 21, 2014

    @mifoss

    i have the same Problem. I have created a self-sigend certifcate but socketio won't connect to my server...

    When i listen to the "EVENT_CONNECT_ERROR" Event i get the following ErrorMessage:

    "com.github.nkzawa.engineio.client.EngineIOException: xhr poll error"

    ------------- ServerCode ( Snippet ) -------------

    express = require('express'),
    app = express(),
    https = require('https').createServer({
        key: fs.readFileSync('server.key'),
        cert: fs.readFileSync('server.crt'),
        ca: fs.readFileSync('server.csr'),
    }, app);
    io = require('socket.io')(https);
    
    https.listen(config.port, function() {
        console.log('Listening on Port %d', config.port);
    });
    
    

    Java-Client:

    IO.Options options = new IO.Options();
    try {
        options.sslContext = createSSLContext();
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    options.secure = true;
    
    TokenManager tokenManager = new TokenManager(); 
    String token = tokenmanager.getToken();
    
    socket = IO.socket(Globals.HOST + "/?token=" + token, options);
    
    socket.on(socket.EVENT_CONNECT, new Emitter.Listener() {
    
    @Override
    public void call(Object... args) {
         Log.d("SOCKETIO", "CONNECTED");
        startMessageListener(socket);
    }
    
    });
    
    public SSLContext createSSLContext() throws GeneralSecurityException, IOException {
        Security.insertProviderAt(new BouncyCastleProvider(), 1);
    
        try {
            TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
    
                @Override
                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }
    
               @Override
               public void checkServerTrusted(X509Certificate[] certs, String authType) {
               }
           } 
    
           // Install the all-trusting trust manager
           SSLContext sc = SSLContext.getInstance("SSL");
           sc.init(null, trustAllCerts, new java.security.SecureRandom()); 
           return sc;
    
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return null;
    }
    

    If i use this code for http-Requets everything works fine

  3. kosch commented on Nov 11, 2014

    @kosch

    I think the problem is maybe related to host name verification. Try to set the

    HttpsURLConnection.setDefaultHostnameVerifier(new RelaxedHostNameVerifier());
    ...
        public static class RelaxedHostNameVerifier implements HostnameVerifier {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        }
    

    Unfortunality such exceptions are not logged. I suggest to add logging at Request.onError including the exception stack.
    Maybe you can add the HostNameVerified as additional Option too.

  4. feromakovi commented on Nov 26, 2014

    @feromakovi

    Hello, I'm using this library too for connecting to server. Connection to server is secured too.
    But in my case I creates SSLContext which should accept all certificates like this:

        private 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 {
            }
        } };
    
        public static class RelaxedHostNameVerifier implements HostnameVerifier {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        }

    and in code I set it up:

        SSLContext sc = SSLContext.getInstance("TLS");
                sc.init(null, trustAllCerts, new SecureRandom());
                IO.setDefaultSSLContext(sc);
                HttpsURLConnection.setDefaultHostnameVerifier(new RelaxedHostNameVerifier());

    and I create custom IO.Options:

        IO.Options options = new IO.Options();
                options.sslContext = sc;
                options.secure = true;
                options.port = 443;

    and for establishing connection I use this code, maybe very similar as the code from samples:

     Socket socket = IO.socket("https://before.host.com", options);
                socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
                    @Override
                    public void call(Object... args) {
                        Log.d(TAG, "eventConnect");
                    }
                }).on(Socket.EVENT_MESSAGE, new Emitter.Listener() {
                    @Override
                    public void call(Object... args) {
                        Log.d(TAG, "eventMessage");
                    }
                }).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
                    @Override
                    public void call(Object... args) {
                        Log.d(TAG, "eventDisconnect");
                    }
                }).on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener() {
                    @Override
                    public void call(Object... args) {
                        Log.d(TAG, "eventConnectError");
                        for(Object o : args){
                            Log.d(TAG, "object: " + o.toString());
                            if(o instanceof SocketIOException)
                                ((SocketIOException) o).printStackTrace();
                        }
                    }
                }).on(Socket.EVENT_ERROR, new Emitter.Listener() {
                    @Override
                    public void call(Object... args) {
                        Log.d(TAG, "eventError");
                    }
                });
                socket.connect();

    And this instantly gives me an Exception, the same as in previous cases:

    com.github.nkzawa.engineio.client.EngineIOException: xhr poll error

    And if I create my own server app, unsecured with scheme - http, on my private network, everything works. Is it problem on client side (me) or server side?
    Thank you for your advices!

  5. crossle commented on Dec 10, 2014

    @crossle

    How about https connect?

  6. jonathanve commented on Dec 10, 2014

    @jonathanve

    Hi @feromakovi and @crossle I was able to communicate from my android phone via ssl. Here it is the project I setup for you guys to try it out.

    https://github.com/jonathanve/socket-io-android

    Hope it helps.

  7. jonathanve commented on Dec 10, 2014

    @jonathanve

    I wrote the code inside my application class. Anywhere else where should I locate it instead?

  8. jonathanve commented on Dec 15, 2014

    @jonathanve
  9. nkzawa commented on Dec 16, 2014

    @nkzawa
    Contributor

    @jonathanve what's your problem?

  10. nkzawa commented on Dec 16, 2014

    @nkzawa
    Contributor

    @jonathanve btw, thank you for your great example app 👍

  11. jonathanve commented on Dec 16, 2014

    @jonathanve

    hi @nkzawa , thank you. Hope the example helps somebody so this issue can be closed

  12. madhumita1 commented on Dec 30, 2014

    @madhumita1

    @nkzawa ,@jonathanve

    how to handle for "https" connections?

  13. j54n1n commented on Jan 14, 2015

    @j54n1n

    Hello,
    I'm also trying to use https connection on my Android client but I get either the dreaded xhr poll error on JellyBean+ or a strange semi working behaviour on Gingerbread or IceCreamSandwich.

    I've running on a Raspberry Pi a simple node.js app that runs Express to serve a webpage embedded with the client side socket.io script.

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8">
      <title>Title</title>
      <script src="/socket.io/socket.io.js"></script>
    </head>
    <body>
    <h1>Content of the document</h1>
    <script>
    var div = document.createElement('div');
    var socket = io.connect('https://raspberrypi/');
    socket.on('secure_data', function(secure_data) {
      console.log(secure_data);
      var p = document.createElement('p');
      p.appendChild(document.createTextNode('' + secure_data));
      document.body.appendChild(p);
    });
    </script>
    </body>
    </html>

    and with the https server app

    var fs       = require('fs');
    var https    = require('https');
    var express  = require('express');
    var socketio = require('socket.io');
    
    var port = 443;
    var app  = express();
    
    var server = https.createServer({
            key: fs.readFileSync('server.key'),
            cert: fs.readFileSync('server.crt')
    }, app).listen(port, function() {
            console.log('Listening on *:' + port);
    });
    
    app.use(express.static(__dirname + '/public'));
    
    var io = socketio(server);
    
    io.on('connection', function(socket) {
            setInterval(function() {
                    socket.emit('secure_data', { hello: 'secure_world' });
            }, 1000);
    });

    I'm generating the keys and ca with a script via openssl

    #!/bin/bash
    openssl genrsa -des3 -passout pass:x -out server.pass.key 2048
    openssl rsa -passin pass:x -in server.pass.key -out server.key
    rm server.pass.key
    # When the openssl req command asks for a "challenge password",
    # just press return, leaving the password empty.
    openssl req -new -key server.key -out server.csr
    # Generate SSL certificate.
    openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

    then I copied the .crt file to my Android Studio project and tried to load the self signed certificate as mentioned in the docs of Android.
    https://developer.android.com/training/articles/security-ssl.html#UnknownCa

    private void getSocketIO() {
            final String uri = "https://raspberrypi/";
            try {
                // Load CAs from an InputStream.
                CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
                Certificate certificate = certificateFactory.generateCertificate(
                        getResources().openRawResource(R.raw.server)); // from file server.crt
                // Create a KeyStore containing the trusted CAs.
                KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
                keyStore.load(null, null);
                keyStore.setCertificateEntry("ca", certificate);
                // Create a TrustManager that trusts the CAs in KeyStore.
                TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
                        TrustManagerFactory.getDefaultAlgorithm());
                trustManagerFactory.init(keyStore);
                // Create an SSLContext that uses the TrustManager.
                SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
                Log.i(uri, "sslContext created");
                //
                // Try to open url.
                URL url = new URL(uri);
                final HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
                httpsURLConnection.setSSLSocketFactory(sslContext.getSocketFactory());
                httpsURLConnection.setHostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        Log.i("HostnameVerifier", "Approving certificate for " + hostname);
                        return true; // Do nothing.
                    }
                });
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            BufferedReader in = new BufferedReader(new InputStreamReader(
                                    httpsURLConnection.getInputStream()));
                            Log.i("httpsURLConnection", "url connected");
                            String line; //FIXME: readLine kicks in socket.io at least on gingerbread!?
                            while((line = in.readLine()) != null) {
                                Log.i("httpsURLConnection", line);
                            }
                            in.close();
                        } catch (IOException e) {
                        }
                    }
                }).start();
                //
                // Try to use socket.io library.
                IO.setDefaultSSLContext(sslContext);
                IO.Options options = new IO.Options();
                options.secure = true;
                options.sslContext = sslContext;
                Socket socket = IO.socket(uri, options);
                socket.on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener() {
                    @Override
                    public void call(Object... args) {
                        for(Object o : args) {
                            Log.i("IO " + Socket.EVENT_CONNECT_ERROR, o.toString());
                        }
                    }
                }).on(Socket.EVENT_CONNECT_TIMEOUT, new Emitter.Listener() {
                    @Override
                    public void call(Object... args) {
                        Log.i("IO", Socket.EVENT_CONNECT_TIMEOUT);
                    }
                }).on(Socket.EVENT_CONNECT, new Emitter.Listener() {
                    @Override
                    public void call(Object... args) {
                        Log.i("IO", Socket.EVENT_CONNECT);
                    }
                }).on("secure_data", new Emitter.Listener() {
                    @Override
                    public void call(Object... args) {
                        Log.i("IO secure_data", args[0].toString());
                    }
                });
                socket.connect();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    First thing was to add

    <uses-permission android:name="android.permission.INTERNET"/>

    in the manifest file.

    To be sure that the certificate part was working I added the code to open a https connection and I printed out in the log the content of the html file. That worked fine without problems. But in the part of your socket.io library I got only "com.github.nkzawa.engineio.client.EngineIOException: xhr poll error" at least from JellyBean till Lollipop.

    In another way Gingebread and ICS had a different behaviour: the socket.io library connected to the server without problems but only if I left the code inplace that was reading from the https input stream.
    My wild guess would be that the javascript inside from the html file gets executed in some way and then kicks in the java socket.io library!?

    I'm attaching the logs that I made:

    From JellyBean till Lollipop

    01-14 16:14:22.716    2654-2654/it.js.ssocketio I/https://raspberrypi/﹕ sslContext created
    ...
    01-14 16:14:22.900    2654-2669/it.js.ssocketio I/HostnameVerifier﹕ Approving certificate for raspberrypi
    ...
    01-14 16:14:23.022    2654-2678/it.js.ssocketio I/IO connect_error﹕ com.github.nkzawa.engineio.client.EngineIOException: xhr poll error
    01-14 16:14:23.027    2654-2669/it.js.ssocketio I/httpsURLConnection﹕ url connected
    01-14 16:14:23.292    2654-2669/it.js.ssocketio I/httpsURLConnection﹕ <!DOCTYPE html>
    01-14 16:14:23.292    2654-2669/it.js.ssocketio I/httpsURLConnection﹕ <html>
    01-14 16:14:23.292    2654-2669/it.js.ssocketio I/httpsURLConnection﹕ <head>
    01-14 16:14:23.292    2654-2669/it.js.ssocketio I/httpsURLConnection﹕ <meta charset="UTF-8">
    01-14 16:14:23.292    2654-2669/it.js.ssocketio I/httpsURLConnection﹕ <title>Title</title>
    01-14 16:14:23.292    2654-2669/it.js.ssocketio I/httpsURLConnection﹕ <script src="/socket.io/socket.io.js"></script>
    01-14 16:14:23.292    2654-2669/it.js.ssocketio I/httpsURLConnection﹕ </head>
    01-14 16:14:23.292    2654-2669/it.js.ssocketio I/httpsURLConnection﹕ <body>
    01-14 16:14:23.292    2654-2669/it.js.ssocketio I/httpsURLConnection﹕ <h1>Content of the document</h1>
    01-14 16:14:23.292    2654-2669/it.js.ssocketio I/httpsURLConnection﹕ <script>
    01-14 16:14:23.292    2654-2669/it.js.ssocketio I/httpsURLConnection﹕ var div = document.createElement('div');
    01-14 16:14:23.292    2654-2669/it.js.ssocketio I/httpsURLConnection﹕ var socket = io.connect('https://raspberrypi/');
    01-14 16:14:23.292    2654-2669/it.js.ssocketio I/httpsURLConnection﹕ socket.on('secure_data', function(secure_data) {
    01-14 16:14:23.292    2654-2669/it.js.ssocketio I/httpsURLConnection﹕ console.log(secure_data);
    01-14 16:14:23.292    2654-2669/it.js.ssocketio I/httpsURLConnection﹕ var p = document.createElement('p');
    01-14 16:14:23.292    2654-2669/it.js.ssocketio I/httpsURLConnection﹕ p.appendChild(document.createTextNode('' + secure_data));
    01-14 16:14:23.292    2654-2669/it.js.ssocketio I/httpsURLConnection﹕ document.body.appendChild(p);
    01-14 16:14:23.292    2654-2669/it.js.ssocketio I/httpsURLConnection﹕ });
    01-14 16:14:23.292    2654-2669/it.js.ssocketio I/httpsURLConnection﹕ </script>
    01-14 16:14:23.292    2654-2669/it.js.ssocketio I/httpsURLConnection﹕ </body>
    01-14 16:14:23.292    2654-2669/it.js.ssocketio I/httpsURLConnection﹕ </html>
    ...
    01-14 16:14:24.063    2654-2683/it.js.ssocketio I/IO connect_error﹕ com.github.nkzawa.engineio.client.EngineIOException: xhr poll error
    01-14 16:14:26.092    2654-2687/it.js.ssocketio I/IO connect_error﹕ com.github.nkzawa.engineio.client.EngineIOException: xhr poll error
    ...
    
    $ sudo DEBUG=* node index.js
      express:application compile etag weak +0ms
      express:application compile query parser extended +46ms
      express:application compile trust proxy false +9ms
      express:application booting in development mode +7ms
      express:router use / query +277ms
      express:router:layer new / +5ms
      express:router use / expressInit +11ms
      express:router:layer new / +2ms
      express:router use / serveStatic +5ms
      express:router:layer new / +1ms
      socket.io:server initializing namespace / +0ms
      socket.io:server creating engine.io instance with opts {"path":"/socket.io"} +53ms
      socket.io:server attaching client serving req handler +45ms
    Listening on *:443
      express:router dispatching GET / +22s
      express:router query  : / +29ms
      express:router expressInit  : / +9ms
      express:router serveStatic  : / +7ms
      send stat "/home/pi/secure-webapp/public/index.html" +27ms
      send pipe "/home/pi/secure-webapp/public/index.html" +20ms
      send modified Wed, 14 Jan 2015 15:34:02 GMT +11ms
      send etag W/"203-3867020799" +12ms
      send content-type text/html +6ms

    For Gingerbread and ICS

    01-14 16:31:27.709    1795-1795/it.js.ssocketio I/https://raspberrypi/﹕ sslContext created
    ...
    01-14 16:31:27.869    1795-1815/it.js.ssocketio I/IO connect_error﹕ com.github.nkzawa.engineio.client.EngineIOException: xhr poll error
    ...
    01-14 16:31:27.909    1795-1809/it.js.ssocketio I/HostnameVerifier﹕ Approving certificate for raspberrypi
    01-14 16:31:27.949    1795-1809/it.js.ssocketio I/httpsURLConnection﹕ url connected
    ...
    01-14 16:31:28.179    1795-1809/it.js.ssocketio I/httpsURLConnection﹕ <!DOCTYPE html>
    01-14 16:31:28.189    1795-1809/it.js.ssocketio I/httpsURLConnection﹕ <html>
    01-14 16:31:28.189    1795-1809/it.js.ssocketio I/httpsURLConnection﹕ <head>
    01-14 16:31:28.189    1795-1809/it.js.ssocketio I/httpsURLConnection﹕ <meta charset="UTF-8">
    01-14 16:31:28.189    1795-1809/it.js.ssocketio I/httpsURLConnection﹕ <title>Title</title>
    01-14 16:31:28.189    1795-1809/it.js.ssocketio I/httpsURLConnection﹕ <script src="/socket.io/socket.io.js"></script>
    01-14 16:31:28.189    1795-1809/it.js.ssocketio I/httpsURLConnection﹕ </head>
    01-14 16:31:28.189    1795-1809/it.js.ssocketio I/httpsURLConnection﹕ <body>
    01-14 16:31:28.189    1795-1809/it.js.ssocketio I/httpsURLConnection﹕ <h1>Content of the document</h1>
    01-14 16:31:28.189    1795-1809/it.js.ssocketio I/httpsURLConnection﹕ <script>
    01-14 16:31:28.189    1795-1809/it.js.ssocketio I/httpsURLConnection﹕ var div = document.createElement('div');
    01-14 16:31:28.189    1795-1809/it.js.ssocketio I/httpsURLConnection﹕ var socket = io.connect('https://raspberrypi/');
    01-14 16:31:28.189    1795-1809/it.js.ssocketio I/httpsURLConnection﹕ socket.on('secure_data', function(secure_data) {
    01-14 16:31:28.189    1795-1809/it.js.ssocketio I/httpsURLConnection﹕ console.log(secure_data);
    01-14 16:31:28.189    1795-1809/it.js.ssocketio I/httpsURLConnection﹕ var p = document.createElement('p');
    01-14 16:31:28.199    1795-1809/it.js.ssocketio I/httpsURLConnection﹕ p.appendChild(document.createTextNode('' + secure_data));
    01-14 16:31:28.199    1795-1809/it.js.ssocketio I/httpsURLConnection﹕ document.body.appendChild(p);
    01-14 16:31:28.199    1795-1809/it.js.ssocketio I/httpsURLConnection﹕ });
    01-14 16:31:28.199    1795-1809/it.js.ssocketio I/httpsURLConnection﹕ </script>
    01-14 16:31:28.199    1795-1809/it.js.ssocketio I/httpsURLConnection﹕ </body>
    01-14 16:31:28.199    1795-1809/it.js.ssocketio I/httpsURLConnection﹕ </html>
    ...
    01-14 16:31:28.949    1795-1825/it.js.ssocketio I/IO﹕ connect
    01-14 16:31:30.009    1795-1828/it.js.ssocketio I/IO secure_data﹕ {"hello":"secure_world"}
    01-14 16:31:30.939    1795-1831/it.js.ssocketio I/IO secure_data﹕ {"hello":"secure_world"}
    ...
    
    $ sudo DEBUG=* node index.js
      express:application compile etag weak +0ms
      express:application compile query parser extended +46ms
      express:application compile trust proxy false +9ms
      express:application booting in development mode +7ms
      express:router use / query +277ms
      express:router:layer new / +5ms
      express:router use / expressInit +11ms
      express:router:layer new / +2ms
      express:router use / serveStatic +5ms
      express:router:layer new / +1ms
      socket.io:server initializing namespace / +0ms
      socket.io:server creating engine.io instance with opts {"path":"/socket.io"} +53ms
      socket.io:server attaching client serving req handler +45ms
    Listening on *:443
      express:router dispatching GET / +45s
      express:router query  : / +30ms
      express:router expressInit  : / +9ms
      express:router serveStatic  : / +6ms
      send stat "/home/pi/secure-webapp/public/index.html" +27ms
      send pipe "/home/pi/secure-webapp/public/index.html" +73ms
      send modified Wed, 14 Jan 2015 15:34:02 GMT +11ms
      send etag W/"203-3867020799" +12ms
      send content-type text/html +6ms
      engine intercepting request for path "/socket.io/" +0ms
      engine handling "GET" http request "/socket.io/?EIO=3&transport=polling" +14ms
      engine handshaking client "P7_8gm23I5Ol-7UBAAAA" +60ms
      engine:socket sending packet "open" ({"sid":"P7_8gm23I5Ol-7UBAAAA","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":60000}) +22ms
      engine:polling setting request +19ms
      engine:socket flushing buffer to transport +3ms
      engine:polling writing "      �0{"sid":"P7_8gm23I5Ol-7UBAAAA","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":60000}" +33ms
      engine:socket executing batch send callback +21ms
      socket.io:server incoming connection with id P7_8gm23I5Ol-7UBAAAA +45s
      socket.io:client connecting to namespace / +0ms
      socket.io:namespace adding socket to nsp / +0ms
      socket.io:socket socket connected - writing packet +0ms
      socket.io:socket joining room P7_8gm23I5Ol-7UBAAAA +3ms
      socket.io:client writing packet {"type":0,"nsp":"/"} +48ms
      socket.io-parser encoding packet {"type":0,"nsp":"/"} +0ms
      socket.io-parser encoded {"type":0,"nsp":"/"} as 0 +4ms
      engine:socket sending packet "message" (0) +77ms
      socket.io:socket joined room P7_8gm23I5Ol-7UBAAAA +33ms
      engine intercepting request for path "/socket.io/" +19ms
      engine handling "GET" http request "/socket.io/?EIO=3&sid=P7_8gm23I5Ol-7UBAAAA&transport=polling" +2ms
      engine setting new request for existing client +6ms
      engine:polling setting request +2ms
      engine:socket flushing buffer to transport +3ms
      engine:polling writing "�40" +5ms
      engine:socket executing batch send callback +9ms
      engine intercepting request for path "/socket.io/" +30ms
      engine handling "GET" http request "/socket.io/?EIO=3&sid=P7_8gm23I5Ol-7UBAAAA&transport=polling" +2ms
      engine setting new request for existing client +4ms
      engine:polling setting request +2ms
      socket.io:client writing packet {"type":2,"data":["secure_data",{"hello":"secure_world"}],"nsp":"/"} +1s
      socket.io-parser encoding packet {"type":2,"data":["secure_data",{"hello":"secure_world"}],"nsp":"/"} +1s
      socket.io-parser encoded {"type":2,"data":["secure_data",{"hello":"secure_world"}],"nsp":"/"} as 2["secure_data",{"hello":"secure_world"}] +3ms
      engine:socket sending packet "message" (2["secure_data",{"hello":"secure_world"}]) +950ms
      engine:socket flushing buffer to transport +2ms
      engine:polling writing "�42["secure_data",{"hello":"secure_world"}]" +3ms
      engine intercepting request for path "/socket.io/" +25ms
      engine handling "GET" http request "/socket.io/?EIO=3&sid=P7_8gm23I5Ol-7UBAAAA&transport=polling" +2ms
      engine setting new request for existing client +3ms
      engine:polling setting request +2ms
      engine:socket executing batch send callback +2ms
      socket.io:client writing packet {"type":2,"data":["secure_data",{"hello":"secure_world"}],"nsp":"/"} +1s
      socket.io-parser encoding packet {"type":2,"data":["secure_data",{"hello":"secure_world"}],"nsp":"/"} +1s
      socket.io-parser encoded {"type":2,"data":["secure_data",{"hello":"secure_world"}],"nsp":"/"} as 2["secure_data",{"hello":"secure_world"}] +2ms
      engine:socket sending packet "message" (2["secure_data",{"hello":"secure_world"}]) +1s
      engine:socket flushing buffer to transport +2ms
      engine:polling writing "�42["secure_data",{"hello":"secure_world"}]" +3ms
      engine intercepting request for path "/socket.io/" +99ms
      engine handling "GET" http request "/socket.io/?EIO=3&sid=P7_8gm23I5Ol-7UBAAAA&transport=polling" +2ms
      engine setting new request for existing client +3ms
      engine:polling setting request +2ms
      engine:socket executing batch send callback +2ms
      socket.io:client writing packet {"type":2,"data":["secure_data",{"hello":"secure_world"}],"nsp":"/"} +1s
      socket.io-parser encoding packet {"type":2,"data":["secure_data",{"hello":"secure_world"}],"nsp":"/"} +1s
      socket.io-parser encoded {"type":2,"data":["secure_data",{"hello":"secure_world"}],"nsp":"/"} as 2["secure_data",{"hello":"secure_world"}] +2ms
      engine:socket sending packet "message" (2["secure_data",{"hello":"secure_world"}]) +923ms
      engine:socket flushing buffer to transport +1ms
      engine:polling writing "�42["secure_data",{"hello":"secure_world"}]" +3ms
    ...

    No clue if I missed something else!?

  14. j54n1n commented on Jan 14, 2015

    @j54n1n

    Ok that was fast xD.
    In the end it was something that I missed in the code.
    The line after IO.setDefaultSSLContext() you have to put

                HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                });

    or provide your own implementation of the HostnameVerifier interface. Pay attention that this is the global setting via the static method HttpsURLConnection#setDefaultHostnameVerifier. Maybe it should be mentioned in the readme?

  15. hgshoggins commented on Jan 25, 2015

    @hgshoggins

    Hello,

    On my side, everything is good until Android Lollipop : stumbled accross a "timeout" SocketIOException, and I can't figure out why.

    Any ideas ?

  16. wingoku commented on Apr 28, 2015

    @wingoku

    @hgshoggins Did you find any solutions for TimeOut issue on Lollipop devices? My code is working fine on pre lollipop devices but on lollipop it is giving me timeout issue.

  17. hgshoggins commented on Apr 29, 2015

    @hgshoggins

    Hello @wingoku. No luck on my side, I had to use plain text on my ws, and make sure I was not transporting any sensitive data.

    I first wanted to use it because in plain HTTP, some GSM BTS mangle the content sent by a Device : I got myself with some strange X-NOKIA-xxxx headers that I did not want to be added, that is why I preferred to use HTTPS.

  18. nkzawa commented on May 2, 2015

    @nkzawa
    Contributor

    Can you try just released v0.5.0 which the websocket transport is replaced with OkHttp ?

  19. najeebullahshah commented on Jun 5, 2015

    @najeebullahshah

    @j54n1n great man, your's is the best solution on the issue of https connection.

  20. shuoli84 commented on Jun 24, 2015

    @shuoli84

    I am using this with HTTPS and it requires no hacking or workaround. Using v0.5.1.

    @anshulvij @nkzawa is it ok to close this?

  21. therockorchid commented on Aug 13, 2015

    @therockorchid

    @shuoli84 ,
    can you share your connection code? Perhaps that would help me figure out what I am doing wrong? Coz I am having the same issue as mentioned above by @j54n1n

    com.github.nkzawa.engineio.client.EngineIOException: xhr poll error

    I am using v0.5.2

  22. marekyggdrasil commented on Oct 19, 2015

    @marekyggdrasil

    I was also having xhr poll error, what resolved the issue was:
    @jonathanve code and also updating socket.io library from v0.3.0 to v0.6.2. I did not establish SSL security within node.js like @j54n1n suggested, instead I defined them in my nginx server configuration.

  23. wpq2014 commented on Jun 11, 2016

    @wpq2014
  24. jonathanve commented on Jun 11, 2016

    @jonathanve

    @wpq2014 yes, let me restore it then. Since no comments were posted since October 2015, I thought It was not longer needed.

  25. dominguesr commented on Sep 23, 2016

    @dominguesr

    @marekyggdrasil could you please explain how you did it on Nginx? We have a similar situation and we haven't been able to figure out how to fix it. thanks

  26. HeartIsBeat commented on Jul 27, 2017

    @HeartIsBeat

    I cause the problem, just use code
    image
    When "io.socket.engineio.client.EngineIOException: xhr poll error" is appeared,for I use emit method's second param is String not JSONObject.
    Connect to socket.io server use java api caused me one day! O my god.

  27. darrachequesne commented on Apr 25, 2021

    @darrachequesne
    Member

    Closed due to inactivity, please reopen if needed.

  28. Oytunkdnz commented on Aug 31, 2022

    @Oytunkdnz

    hello!

    I get this strange error:

    E/Socket: Socket connection can not be established

    my SocketHelper.java is:

    private SocketHelper() {

    try {

            IO.Options options = new IO.Options();
            options.forceNew = true;
    
    
            socket = IO.socket(SOCKET_URL, options);
    
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
    

    and error comes from VehicleBidFragmentPresenterImp.java is:

    public void initSocketHelper(String userId, int auctionId) {
    SocketHelper.getInstance().connect(new SocketHelper.SocketCallBack() {
    @OverRide
    public void onConnect(Object... args) {
    // send first bid for wake up socket
    sendBid(userId, 4, "1", String.valueOf(auctionId), Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis());
    }

            @Override
            public void onDisConnect(Object... args) {
                Log.d("Socket", "Socket connection close");
            }
    
    
            @Override
            public void onError(Object... args) {
                Log.e("Socket", "Socket connection can not be established");
            }
    
    
            @Override
            public void onTimeOut(Object... args) {
                if (getView() != null && getView().get() != null)
                    getView().get().bidError("Bağlantınız zaman aşımına uğradı lütfen tekrar bağlanmayı deneyiniz.");
            }
    
    
            @Override
            public void onBidError(Object... args) {
    
                if (args != null && args.length > 0) {
                    try {
                        for (Object data : args) {
    
                            if (data == null)
                                break;
    
                            AuctionBidErrorModel bidModel = parseSocketError(data.toString());
    
                            if (bidModel == null) {
                                getView().get().bidError("Bir hata oluştu daha sonra tekrar deneyiniz.");
                                return;
                            }
    
                            long id = bidModel.getAuctionId();
    
                            if (id == auctionId && userId.equals(bidModel.getKey())) {
    
                                Log.d("Socket", " Error --> " + data.toString());
    
                                getView().get().bidError(bidModel.getMessage());
                            }
                        }
                    } catch (Exception ignore) {
                        ignore.printStackTrace();
                    }
                }
            }
    
            @Override
            public void onBidPublish(Object... args) {
                try {
                    if (getView() != null && getView().get() != null) {
    
                        for (Object data : args) {
    
                            if (data == null)
                                break;
    
                            AuctionBidModel bidModel = parseSocket(data.toString());
    
                            if (bidModel == null) {
                                getView().get().bidError("Bir hata oluştu daha sonra tekrar deneyiniz.");
                                return;
                            }
    
                            long id = bidModel.getAuctionId();
    
                            if (id == auctionId && bidModel.getSendType() != 4) {
    
                                Log.d("Socket", " BidPublish --> " + data.toString());
    
                                getView().get().bidSend(bidModel);
                            }
                        }
    
                    }
                } catch (Exception ignore) {
                    ignore.printStackTrace();
                }
            }
    
            @Override
            public void onClose(Object... args) {
    
                try {
                    if (args != null)
                        Log.d("SocketHelper", "" + Arrays.toString(args));
    
                    if (getView() != null && getView().get() != null && args != null) {
    
                        for (Object data : args) {
    
                            if (data == null)
                                break;
    
                            AuctionBidModel bidModel = parseSocket(data.toString());
    
                            if (bidModel == null) {
                                return;
                            }
    
                            long id = bidModel.getAuctionId();
    
                            if (id == auctionId && bidModel.getSendType() != 4) {
    
                                Log.d("Socket", " Close --> " + data.toString());
    
                                getView().get().auctionClose();
                            }
                        }
    
                    }
                } catch (Exception ignore) {
                    ignore.printStackTrace();
                }
    
            }
    
    
            @Override
            public void autoSellCancel(Object... args) {
                try {
                    if (args != null)
                        Log.d("SocketHelper", "" + Arrays.toString(args));
    
                    if (getView() != null && getView().get() != null && args != null) {
    
                        for (Object data : args) {
    
                            if (data == null)
                                break;
    
                            AuctionBidModel bidModel = parseSocket(data.toString());
    
                            if (bidModel == null) {
                                return;
                            }
    
                            long id = bidModel.getAuctionId();
    
                            if (id == auctionId && bidModel.getSendType() != 4) {
    
                                Log.d("Socket", " SellCancel --> " + data.toString());
    
                                getView().get().autoSellCancel();
                            }
                        }
    
                    }
                } catch (Exception ignore) {
                    ignore.printStackTrace();
                }
            }
    
            @Override
            public void autoSell(Object... args) {
                try {
                    if (args != null)
                        Log.d("SocketHelper", "" + Arrays.toString(args));
    
                    if (getView() != null && getView().get() != null && args != null) {
    
                        for (Object data : args) {
    
                            if (data == null)
                                break;
    
                            AuctionBidModel bidModel = parseSocket(data.toString());
    
                            if (bidModel == null) {
                                return;
                            }
    
                            long id = bidModel.getAuctionId();
    
                            if (id == auctionId && bidModel.getSendType() != 4) {
    
                                Log.d("Socket", " AutoSell --> " + data.toString());
    
                                getView().get().autoSell();
                            }
                        }
    
                    }
                } catch (Exception ignore) {
                    ignore.printStackTrace();
                }
            }
    
            @Override
            public void auctionCounterUpdate(Object... args) {
                try {
                    if (args != null)
                        Log.d("SocketHelper", "" + Arrays.toString(args));
    
                    if (getView() != null && getView().get() != null && args != null) {
    
                        for (Object data : args) {
    
                            if (data == null)
                                break;
    
                            AuctionBidModel bidModel = parseSocket(data.toString());
    
                            if (bidModel == null) {
                                return;
                            }
    
                            long id = bidModel.getAuctionId();
    
                            if (id == auctionId && bidModel.getSendType() != 4) {
    
                                Log.d("Socket", " CounterUpdate --> " + data.toString());
    
                                getView().get().auctionCounterUpdate(bidModel.getNewTotalSeconds());
                            }
                        }
    
                    }
                } catch (Exception ignore) {
                    ignore.printStackTrace();
                }
            }
        });
    }
    

    please help me to solve this problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions