0

I have a socket.io server which listens to sockets:

io.on('connection', (socket) => {
    socket.on('myEvent', function(data){
        socket.emit('eventReceived', { status: 1 });
    });
});

I know that Node.js and Socket.IO is not working in multithreading, so I wonder how to effectively handle multiple clients, sending a myEvent at the same time.

I've read a few things about Clusters. Would it be as easy as just adding the following code infront of my project?

const cluster = require('cluster');
const os = require('os');
const socketIO = require('socket.io');

if (cluster.isMaster) {
  const numCPUs = os.cpus().length;
  console.log(`Master ${process.pid} is running`);

  // Fork workers
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', (worker, code, signal) => {
    console.log(`Worker ${worker.process.pid} died`);
  });
} else {
  //my socket code
}

I've also read a few things about Redis, how would it be useful in such a case? Is it effective on an Raspberry Pi? Would it be possible to create a new thread for each user?

Thanks for any help :)

4
  • I don't think you need multi threading to handle "multiple clients, sending a myEvent at the same time". Use rooms per user/account (need authentication) and io.to("<user-id>").emit("some event"); to send event. Commented Mar 31, 2024 at 17:12
  • @bogdanoff I've read that if multiple clients connect to my server at the same time and send the myEvent, the server will handle them one by one and not multithreaded. So if for example 1000 clients connect at the same time it can lag a lot for the last client. Commented Mar 31, 2024 at 17:22
  • Where did you read that, can you share link ? Thats not how event loop of nodejs works. Your statement is true when you block the event loop (like calling synchronous I/O, while loop and lengthy for loop) and this not only applies to websockets but also to http/tcp as well . Commented Apr 1, 2024 at 2:44
  • @bogdanoff stackoverflow.com/questions/9362823/… Commented Apr 1, 2024 at 9:50

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.