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 .
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.
Besides: emitting and listening to events. broadcasting events.
CLIENT SIDE CODE:var socket = io. connect('http://localhost'); socket. on('start', function (data) { $("#pointer"). animate({ 'top': data["y"], 'left': data["x"] }, 0); }); socket.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With