Search code examples
androidcookiesheadersocket.iohandshaking

Android / Socket.io client - How to send a cookie while handshaking with the server?


I'm trying (unsuccessfully) to connect with a socket.io server, but I keep getting the same errors : io.socket.SocketIOException: Error while handshaking caused by java.net.ConnectException: failed to connect to my.domain.name.com (port 8080) after 10000ms: isConnected failed: ECONNREFUSED (Connection refused).

I just discovered that I'm supposed to send a cookie with the following values when handshaking : the domain, the path, the name and the value. After trying several potential ways to do it (based on this and this), I ended up with that piece of code, but it still not working :

String cookieString = "domain=" + "my.domain.name.com" + ";path=" + "/" + ";name=" + "auth" + ";value=" + "XXXXXtokenXXXXX";
CookieManager.getInstance().setCookie("http://my.domain.name.com:8080/", cookieString);

String header = CookieManager.getInstance().getCookie("my.domain.name.com:8080/");
final SocketIO socket = new SocketIO("my.domain.name.com:8080/");
socket.addHeader("Cookie", header);

socket.connect(new IOCallback()
{
    ...
}

CookieManager.getInstance().getCookie(...) keeps returning null and the connection is still failing.

Could anybody help me add a cookie to the header please?

And for the record, I don't know what it could change, but I'm using this lib : https://github.com/Gottox/socket.io-java-client

Thanks in advance for your help !

Mathieu


Solution

  • Ok, just in case anybody would need the solution, I finally fixed this. It's actually pretty simple :

            String cookie = "domain=\"http://my.domain.name.com:80\";path=\"/\";name=\"auth\";value=\"XXXXtokenXXXX\"";
            socket = new SocketIO("http://my.domain.name.com:80/");
            socket.addHeader("Cookie", cookie);
    
            socket.connect(new IOCallback()
            {
                ...
            }
    

    So you just have to create a string of the form "key1=value1;key2=value2..." and to add it as a header to the socket with the method addHeader("Cookie", youCookieString);.

    And for the record, I kept getting the error ECONNREFUSED because I was trying to connect on the WRONG PORT (8080 instead of 80)...