Connecting to a specific Server Ip with Socket.io

2020-06-18 09:14发布

问题:

I have to build a crossplatform web app for mobile devices, so I'm developing it with html, css and js (then it will pass through phonegap or cordova).

My problem is working with socket.io, and my questions are:

1) Can I connect to a specific ip on the client-side?

Instead on having this:

 <script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>

I need this, but this doesn't work:

<script src="my-app/folder/js/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://my.server.ip:port');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>

2) On the server side, how can I create a server that listen to connections and messages on its IP?

var io = require('socket.io').listen(80, my.server.ip);

In this way, the application's users will connect to my server Ip in which I host the chat service.

I suppose that I'm not in thinking in the right logic of socket.io .

回答1:

You will not be connecting to localhost when you deploy the application and the devices will be connecting to the server hostname or IP address.

The following code on your server will run socket.io on an IP address associated with the server on the specified port provided that the server is accessible on that IP address

var io = require('socket.io');
var server = http.createServer();
server.listen(port, ipAddress);
var socket = io.listen(server);

The following code should work fine on the client side

var socket = new io.Socket();
socket.connect('http://' + ipAddress + ':' + port);

Make sure you are able to connect to the IP address across the network from the client device for this to work.