Lorenzo von Matterhorn Lorenzo von Matterhorn - 7 months ago 19
Javascript Question

Issues with using Socket.io

I am trying to use socket.io for the first time, Im using it with a MEAN Stack. I have set it up the following way.

Server.js

var express = require('express');
var app = express(); // create our app w/ express
var server = require('http').createServer(app);
var io = require('socket.io')(server);

app.listen(port);

io.on('connection', function(socket) {

socket.emit('message', {
'message': 'hello world'
});
});


HTML File

<script>
var socket = io.connect();

socket.on('message', function(data) {
console.log(data.message);
});
</script>


I couldn't find the
socket.io.js
file so I searched for a CDN for the script. I used the following.

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.6/socket.io.js"></script>


I tried downloading the socket.io.js from their website but the website seems to be down. I can access it, I get the 502 BAD GATEWAY error (http://socket.io)

When I load my HTML page after setting everything up as shown above I get the following error in the console.

enter image description here

Any help will be greatly appreciated!

UPDATE:

enter image description here

Answer

The socket.io server will perform some magic to provide that file when you retrieve it like this:

<script src="/socket.io/socket.io.js"></script>

EDIT: ah, I see the problem: your Express setup is incorrect.

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

app.listen(port);

You're attaching socket.io to a server created by http.createServer, but with app.listen() you're actually creating a new server, one that socket.io isn't attached to.

You can make the setup a bit simpler:

var express = require('express');
var app     = express();
var server  = app.listen(port);
var io      = require('socket.io')(server);

No need to use http.