Home > Software design >  Separation of Socket.io and Express js
Separation of Socket.io and Express js

Time:01-02

Hello everyone and happy holidays!

I'm creating a chat app using socket.io and Express and need some guidance on how to proceed.
As it is now, I have my socket.io module in the same file as my express js file.

And it works fine, but when I started to implement a login page i noticed that when a go to the "localhost:port/" i still get connected to the socket and i get assigned a socket.id.
And it does make sense, I suppose, to start from the top and go to the bottom.

My plan is:

  1. Go through the login page first

  2. Then get redirected to the "localhost:port/MessagingClient" and get a socket.id

How it works now:

  1. Go to the login page, get assigned a socket.id without login in.

  2. Go to "localhost:port/MessagingClient" and get assigned a new socket.id

But since i run everything in 1 js file it doesn't work as i want it to.

My question is how can I split "Login" page and "MessagingClient" page, but still run on the same port?
I imagine I could solve this by running 2 node js processes instead of 1 and use 2 ports, but is that a valid way of doing it?

MessaginServer.js:

const dotenv = require("dotenv").config();
const express = require("express");
const app = require("express")();
const http = require("http").Server(app);
const io = require("socket.io")(http);
const port = process.env.PORT || 3000;
// import { readFromDB } from "./mongoDB.js";
const { readFromDB } = require("./mongoDB");

app.use(express.static(__dirname   "/public/"));
app.get("/", (req, res) => {
  res.sendFile(__dirname   "/Public/LoginClient.html");
});

app.get("/MessagingClient", (req, res) => {
  res.sendFile(__dirname   "/Public/MessaginClient.html");
});

io.on("connection", async (socket) => {
// socket.on("test1", arr1, arr2)=>{};
// socket.on("test2", arr1, arr2)=>{};
})

http.listen(port, () => {
  console.log(`Socket.IO server running at http://localhost:${port}/`);
});

What i have tried:

I tried to move all the socket.io code inside

app.get("/MessagingClient", (req, res) => {
  res.sendFile(__dirname   "/Public/MessaginClient.html");
});

but that resulted in message duplication..

Then I thought about trying to use Npm concurrently, but could not find anything about whether it is okay to use it in a production environment.

Any tips?

CodePudding user response:

you create a socket server in a separate file:

const socketServer = (server) => {
  const io = require("socket.io")(server, {
    cors: {
      origin: "*",
      methods: ["GET", "POST"],
    },
  });

  //set middleware for socket server here before .on
  io.use((socket, next) => {
    yourMiddleware(socket, next);
  });
  // your io connection logic
  io.on("connection", async (socket) => {
    // socket.on("test1", arr1, arr2)=>{};
    // socket.on("test2", arr1, arr2)=>{};
  });
};

module.exports = {
  socketServer,
};

then in app.js

//initialize app
const app = express();
// add your middlewares and routing

const server = http.createServer(app);
// import socketServer
socketServer(server);

server.listen(PORT, () => {
    console.log(`Server is listening on ${PORT}`);
});

CodePudding user response:

you create a socket server in a separate file:

const socketServer = (server) => {
  const io = require("socket.io")(server, {
    cors: {
      origin: "*",
      methods: ["GET", "POST"],
    },
  });

  //set middleware for socket server here before .on
  io.use((socket, next) => {
    yourMiddleware(socket, next);
  });
  // your io connection logic
  io.on("connection", async (socket) => {
    // socket.on("test1", arr1, arr2)=>{};
    // socket.on("test2", arr1, arr2)=>{};
  });
};

module.exports = {
  socketServer,
};

then in app.js

//initialize app
const app = express();
// add your middlewares and routing

const server = http.createServer(app);
// import socketServer
socketServer(server);

server.listen(PORT, () => {
    console.log(`Server is listening on ${PORT}`);
});
  • Related