socket.io icon indicating copy to clipboard operation
socket.io copied to clipboard

doc suggestion: do not use express app.listen() with socket.io

Open jldec opened this issue 11 years ago • 6 comments

I ran into this in the process of adding socket.io to an existing express(4) app because i didn't switch the code from app.listen() to server.listen().

The symptom is refusal by the server to serve the client library or connect any sockets.

According to http://expressjs.com/4x/api.html#app.listen , "This method is identical to node's http.Server.listen()" - but in reality it creates a new http server leaving the one with socket.io non-operational.

Hopefully this issue will help others to avoid the same trap.

jldec avatar Apr 07 '15 17:04 jldec

Could you please provide a full example? Been dealing with these changes due to new express, and it's not obvious to me what the "server" would be in this case, especially when trying to pass in custom "use" settings. Thanks.

asnyder avatar Apr 07 '15 20:04 asnyder

Our original project used regular express boilerplate:

var express = require('express');
var app = express();

// ... other code

app.listen(port);

the socket.io documentation here says

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

server.listen(80);

so i fixed the first part of the code in our project, but i didn't change app.listen() to server.listen() because i thought they were the same, and things kindof worked except socket.io didn't run...

jldec avatar Apr 08 '15 00:04 jldec

+1

Did a bit more research and found a way (more details here) to stick with app.listen():

var io = require("socket.io").listen(server);
app.set("port", (process.env.PORT || 3000));
var server = app.listen(app.get("port"), function(){
  console.log("Server started: http://localhost:" + app.get("port") + "/");
})

which seems to work the same as:

var io = require("socket.io")(server);
var server = require('http').Server(app);
server.listen((process.env.PORT || 3000), function(){
  console.log("Server started: http://localhost:" + app.get("port") + "/");
});

TifPun avatar Oct 13 '16 17:10 TifPun

For folks passing by looking for answer to you CORS issue, express.listen() causes "No 'Access-Control-Allow-Origin' header is present on the requested resource." CORSs error, whereas http.listen() does not.

jakesee avatar Jul 21 '18 10:07 jakesee

This is indeed a common trap... A note was added here: https://socket.io/docs/v3/server-initialization/#With-Express

darrachequesne avatar Feb 17 '21 09:02 darrachequesne

is there any limitations if we use server created from

const expressServer = app.listen(4000)

to implement socket.io server

const io = new Server(expressServer,{
cors: [ 'http://localhost:4000' ] })

sharafath-ali avatar Dec 25 '24 14:12 sharafath-ali