Reputation: 131
I have the the following code which runs without a problem when run on a local network where my friends who are connected on the same network can connect to my system's ip (192.168.0.107) , but how to make this socket.io server code to listen on the static ip I got from an isp provider, so anyone from anywhere can connect to this socket.io server via internet.
Server's code:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res) {
res.sendfile('index.html');
});
users = [];
io.on('connection', function(socket) {
console.log('A user connected');
socket.on('setUsername', function(data) {
console.log(data);
if(users.indexOf(data) > -1) {
socket.emit('userExists', data + ' username is taken! Try some
} else {
users.push(data);
socket.emit('userSet', {username: data});
}
});
socket.on('msg', function(data) {
//Send message to everyone
io.sockets.emit('newmsg', data);
})
});
http.listen(3000, function() {
console.log('listening on localhost:3000');
});
Upvotes: 2
Views: 2860
Reputation: 2246
You can update your call to http.listen
according to the documentation to explicitly listen for requests to a given address:
http.listen(3000, 192.168.0.107, function() {
console.log('listening on localhost:3000');
});
But the default is permissive (accepts requests for any host) so if you are unable to connect its likely due to firewall/NAT issues. From the docs:
If host is omitted, the server will accept connections on the unspecified IPv6 address (::) when IPv6 is available, or the unspecified IPv4 address (0.0.0.0) otherwise.
You need to configure your router to forward requests on whatever port you would like to serve from (usually port 80) to your local IP. This would be more a question for the SuperUser or ServerFault sites.
Upvotes: 1