Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connecting to a specific Server Ip with Socket.io

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 .

like image 988
Andrea Giachetto Avatar asked Apr 07 '14 14:04

Andrea Giachetto


People also ask

Does Socket.IO require a server?

It seems that Socket.IO is always dependent on a http server, to the point that it will create one for you, like in the example above.

Is Socket.IO server side?

Besides: emitting and listening to events. broadcasting events.

How do I run a Socket.IO in localhost?

CLIENT SIDE CODE:var socket = io. connect('http://localhost'); socket. on('start', function (data) { $("#pointer"). animate({ 'top': data["y"], 'left': data["x"] }, 0); }); socket.


1 Answers

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.

like image 136
Shain Padmajan Avatar answered Sep 23 '22 16:09

Shain Padmajan