3

For some hours ive been trying to get socket.io working with express 4. Ive started following this tutorial which gave me a working rest api.

To get socket.io working i used the command

npm install socket.io

This added socket.io to my node_modules dir. After this i've edited my app.js to contain the following code:

//LINE above var app = espress();
var http    =     require('http').Server(app);
var io      =     require("socket.io")(http);
io.on('connection',function(socket){  
    console.log("A user is connected");
});
// my routes etc

In my (jade) view i've added the following code :

script(src="https://cdn.socket.io/socket.io-1.2.0.js")
script.
    var socket = io('http://localhost/');

now when i run with npm start i get the following error in my browser and npm console:

http://localhost:3000/socket.io/?EIO=3&transport=polling&t=1427056664743-51 404 (not found)

As far as i know i do not use express-generator as sugested in almost every answer at related question, what am i doing wrong?

my complete app.js

i've tried this : but the result is an error with port 3000 already in use.

Community
  • 1
  • 1
Sven van den Boogaart
  • 11,833
  • 21
  • 86
  • 169
  • For what it's worth, I don't recommend loading your Socket.IO client from a CDN. If you load from the Socket.IO server itself, you'll get a version matched to the server. That may be the source of your problem here. – Brad Mar 22 '15 at 20:42
  • @Brad i've changed it to a local src (checked and its loading) but still the same error. – Sven van den Boogaart Mar 22 '15 at 20:48
  • For a start it should be `require('http').createServer(handler)` – Matt Harrison Mar 22 '15 at 21:21
  • I believe it should be `http://localhost:3000/socket.io/socket.io.js`. See [here](http://socket.io/docs/) for reference. – majidarif Mar 22 '15 at 21:21

1 Answers1

11

Solved it with thanks to the answer here

var app = express();
var http = require( "http" ).createServer( app );
var io = require( "socket.io" )( http );
http.listen(8080, "127.0.0.1");


io.on('connection',function(socket){  
    console.log("A user is connected");
});

At the client :

script(src='/javascripts/socket.io-1.2.0.js')
script.
    var socket = io.connect( "http://localhost:8080");

Changing ports did the trick (8080 instead of 3000)

Community
  • 1
  • 1
Sven van den Boogaart
  • 11,833
  • 21
  • 86
  • 169
  • 20
    I don't see any reason port 3000 shouldn't work. Seems like the main point of the solution you posted a link to was that using app.listen doesn't work since socket.io can only get the requests from the http server, since socket.io takes the server as its handler and not the express app. – saltthehash Jun 14 '16 at 02:45
  • So what exactly is the client-side code supposed to be? `script.` is out of place, and I can't seem to make out what it's supposed to be. – avisk Jun 28 '21 at 00:51