Connect to socket.io dynamically

2019-08-09 19:46发布

问题:

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

回答1:

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."



回答2:

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