Max Markson
Max Markson

Reputation: 800

Connect to socket.io dynamically

I'm trying to connect the browser to my application via socket.io.

<script type="text/javascript" src="http://localhost:4000/socket.io/socket.io.js"></script>
<script>
    var socket = io.connect('http://localhost:4000');
</script>

With this standard method all works fine. Now I'm trying to transform this connection in "dynamic" based on the IP of the server, something like this:

<html>
    <head>
        var socket;
        function loadFile(filename){
            var ip_server = location.host;
            var body = document.getElementsByTagName( 'body' )[0],
                fileref = document.createElement('script');
            fileref.setAttribute("type","text/javascript");
            fileref.setAttribute("src", "http://"+ip_server+"/"+filename);
            body.appendChild( fileref ); 
        }
    </head>
    <body>
        <script type="text/javascript">
            loadFile("socket.io/socket.io.js");
            socket = io.connect('http://'+location.host);
        </script>
    </body>
</html>

But firebug says ReferenceError: io is not defined on line socket = io.connect('http://'+location.host);.

How can I solve? There's a simple way to do what I'm thinking? Thanks

Upvotes: 1

Views: 2343

Answers (2)

James Amazons
James Amazons

Reputation: 1

const socket = io.connect(location.href);

Upvotes: -1

John Zwinck
John Zwinck

Reputation: 249582

Socket.io has "magical" integration with Node.js which means that something much simpler will work automatically:

<script src="/socket.io/socket.io.js"></script>
var socket = io.connect();

This will find the library and the socket with no explicit host or path. It should "just work."

Upvotes: 8

Related Questions