NodeJs - express and socket.io same port integration

I am creating a server using NodeJs and Express, but I found out that if I want to make a service live, I need to use Socket.io. In this server, there are some service that don't need to be live, and these are implemented using express routes. This are tested and correctly working. Now I have to let some services to be live. So, I think I should implement also socket.io in my server configuration. This is my code without socket.io, working perfectly:

const express = require('express');
const morgan = require('morgan');
const cors = require('cors');
const mongoose = require('mongoose');

require('dotenv').config();

const app = express();
const port = process.env.port || 5050;

app.use(morgan('dev'));

app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended:true }));

const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {useNewUrlParser:true});

const connection = mongoose.connection;
connection.once('open', () => console.log('Connected'));

const routes = require(#every routes);


app.use(routes);//all created routes


app.listen(port, () => {console.log(`Server listening on port ${port}`)});

NOw, I should import correctly socket.io. When it is done, I think I can figure out correctly hot to implement my services. So, I tryied to add the line const io = require('socket.io').listend(app) as I saw in another stackoverflow quesion, but the terminal shows up this error:

const io = require('socket.io').listend(app)
                                ^

TypeError: require(...).listend is not a function

So, I don't know how to integrate this two. I don't know if it is worth to use the same port, or if I should use another port for the socket, but I think the same port would be good. If someone knows how to implement socket.io in my current code, or a way to keep both functionalities, please help me. Thank you so much

1 answer

  • answered 2021-12-05 11:10 jfriend00

    Change this:

    app.listen(port, () => {console.log(`Server listening on port ${port}`)});
    

    to this:

    const httpServer = app.listen(port, () => {console.log(`Server listening on port ${port}`)});
    

    Then, add this:

    const { Server } = require("socket.io");
    const io = new Server(httpServer );
    

    This will let both your Express server and your socket.io server share the same http server. Since all incoming socket.io connections are identifiable with some custom headers, the socket.io code (actually the underlying webSocket transport does this) can grab those and handle them independently from your regular http requests.

    See plenty of examples in the socket.io doc which has improved immensely from its early days.

    Sometimes, it's easy to get confused looking at different examples because there are a dozen different ways to create your http server that you use with Express. The general idea here is that whichever way you use, just make sure you assign the http server instance that you created to a variable that you can then use with socket.io server initialization (as shown above). In your Express code, app is not the server. That's the Express app object which is also an http request handler. It's not the server. The server is something you get from http.createServer() or something that app.listen() returns to you (after calling http.createServer() internally).

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum