xVanjaZ xVanjaZ - 19 days ago 9
Node.js Question

Socket.IO works locally, but not exernally



I am new to Node.js and im trying to complete a simple chat application.

But im stuck. I tried to google and used other solutions, but i cant find it working for some reason. If someone can help me out that will be great.

The error im getting is that it took too long to respond.


Here is my code.

Server side:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

//##### PUSH HTML FILE
app.get('/', function(req, res){
res.sendFile(__dirname +'/index.html');
});

//##### START SERVER
http.listen(3000, '0.0.0.0', function(){
console.log('started on port: 3000');
});

//##### USER CONNECTED
io.on('connection', function(socket){
console.log('A User Connected');

//##### LOG MESSAGE
socket.on('chat message', function(msg){
console.log(msg);
io.emit('chat message', msg);
});

//##### LOG USERNAME
socket.on('set username', function(username){
console.log('NEW USER: ' + username + ' has been set!');
io.emit('set username', username);
});

//#####USER DISCONNECTED
socket.on('disconnect', function(){
console.log('A user disconnected');
});
});


Client side:

<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();

//##### SET USERNAME
$('#set_username').submit(function(){
socket.emit('set username', $('#username').val());
return false;
});

//##### SET MESSAGE
$('#sendmsg').submit(function(){
var msg = '['+$('#username').val()+'] ' + $('#m').val();

socket.emit('chat message', msg);
$('#m').val('');
return false;
});

//SET MESSAGE
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>


Thanks in advance!

Answer

Look at the comments :

You are listening at port 3000 behind a NAT. If you want to connect from outside you need to config port forwarding in your router to your local server. You have a typo in your NAT rule.

Comments