Recently, I have been experimenting with Node.js and Socket.io. Successfully, I have been able to implement these but only on localhost. Now I would like use this functionality on my dedicated server. I am hosting my server from my own home and I cannot get node and socket to run outside of localhost. The importance of this is so that I can use two different computers while testing out my site. Here is my code as follows:
app.js:
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
server.listen(80);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
index.html:
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
These are samples that were taken directly off the socket.io site. Now it works on localhost, but not externally. I cannot use it on another computer. I was advised to change
var socket = io.connect('http://localhost:8080');
to
var socket = io.connect('http://mydomain.com:8080');
, but that makes the browser throw the following errors :
Uncaught ReferenceError: io is not defined mydomain.com/:3
GET http://mydomain.com/socket.io/socket.io.js mydomain.com/:1
even on my main server computer. Im using OSX server with a mac mini btw.
Any advice would be appreciated:
It looks like you're listening on port 80 instead of 8080, and you will need to point your script block to your server, so try
needs to be
or better yet
If that doesn't work, make sure you check for any errors under the network tab of your debugger window (presuming you're using chrome) to make sure you're loading that socket.io.js file correctly.