Search code examples
node.jssocket.ioreal-time

Using socket.io from inside and outside LAN


I am using socket.io for a project that requires me to stream live data to a browser. Now the server part is fine, but on socket.io client io.connect() call, I have had a few problems in the past, without proper resolution. I have tried the usual suspects, but I am not getting through.

My client call to looks like this: var socket = io.connect('http://10.95.xx.xx:5002'); where 10.95. .. is the IP address of the server on the LAN. Using this IP I can access the server from inside the LAN, on any machine in the LAN, but this doesn't work from outside the LAN. Problem being, most probably, that this IP is for LAN only and not the public IP. As per university's network settings, the public IP is 128.95 ...and if I change it to this IP, then it will be accessible from outside, but not from inside.

One way to resolve this, is that I try to read the client's IP address and based on that decide the parameter IP. But this doesn't feel robust. Also, I tried using io.connect("/") . It had worked for me in previous circumstance, but it did not this time. Also, the empty call did not work io.connect() did not work.


Solution

  • As you said you can use the clients IP address, this here always worked for me:

    var port = window.location.port,
        host = window.location.hostname,
        protocol = window.location.protocol,
        path = '/',
        url, 
        options = { };
    
    if( protocol.indexOf( 'https' ) > -1 ) {
        protocol = 'wss:';
    } else {
        protocol = 'ws:'
    }
    
    url = protocol + "//" + host + ":" + port + path;
    
    options = { };
    
    /*
    // If you wanted to add an access token, "Session" is where I store this
    if( Session.token ) {
       options.query = 'access_token=' + Session.token;
    }
    */
    
    socket = io( url, options );