samedi 25 juillet 2020

Is it possible to use socket.io server in a scalable way, in terms of software design?

the context:

I am currently working on a web application, which needs a lot of interactions through real-time data, when on my server made in nodejs, I try to maintain an mvc architecture, I realize that I cannot use socket out of 1 single file, because whenever I call it somewhere else it is not possible to obtain the connection object, to be used within my models.

it is normal to see a socket.io server with this structure (using nodejs):

io.on('connection', function(socket) {
  console.log('Alguien se ha conectado con Sockets');
  socket.emit('messages', messages);

  socket.on('new-message', function(data) {
    messages.push(data);

    io.sockets.emit('messages', messages);
  });
});

the object variable socket that comes within the connection channel is the one that serves socket clients, but outside of that connection I cannot serve it, I have tried that I assign that variable in a sychronic way outside that callback and it is not possible for me, it always arrives null, nor can I use it outside other model files.

Question: Is there a way to be able to make a kind of a singlenton pattern to be able to use this socket object in multiple files?

Aucun commentaire:

Enregistrer un commentaire