Reputation: 2523
I run a server with node.js & socket.io on MacOS to serve different clients in a local network. As far as i understand, the socket.io library has to be loaded first on the clientside as stated in the documention https://socket.io/docs/:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost');
…
</script>
This seems to be only to a proposing template, because this does not work at all (or maybe i did something wrong?)?
So i changed "localhost" to the actual IP address+port of my server (192.168.178.2:3000) and now everything just works fine, especially with different client platforms like MacOS, iOS, Android & Windows (as wanted!).
The problem is, that i want to use the server alternately in different local nets and therefore with changing IP-adresses. But to specify the server address always in that "hardwired" manner manually (!) is very cumbersome and seems not practically. There must be a better solution!
So i did some experiments with logical names. First i added the port:
var socket = io('http://localhost:3000');
This works (at least) but ONLY on the mac itself, where also the server runs!?
Then a little more specific:
var socket = io('http://theNameOfMyMac.local:3000');
Voila, this now works also with external devices! Great! But wait, only with MacOS and iOS, not Windows and Android devices. Too bad, because this would have been a practical solution to my problem! So, i am back at my initial solution where i always have to specify the actual IP address in the HTML file. Nothing else seems to help?
Can someone explain to me why this behaves like this and what could possibly be a solution? Maybe the HTML code could get the (calling!) server address automatically in the HTML file itself? But how?
By the way, should there not be a difference between:
var socket = io('http://192.168.178.2:3000');
and
var socket = io.connect('http://192.168.178.2:3000');
Both work without a noticeable difference!?
Upvotes: 2
Views: 6435
Reputation: 36319
So, to your last question if you just call io()
with no parameters it'll default to the host the HTML was served from.
As for the rest, it's a lot to explain, but I'll try and be brief. You want to read up on networking to get the details.
The bottom line is that the client has to know how to find your server. That means it needs an IP address. It can get that IP address either directly (like you did in your working example), or through hostname resolution.
Hostname resolution happens either by the client looking in it's /etc/hosts file, or by querying it's DNS server for a fully qualified domain name.
Upvotes: 3