Sailsjs - How to set up socket configuration?

I looked into sockets, socket.io and sails yesterday and I must say that I am quite lost. I've never used them before. I thought I understood, but I'm not sure.

I have based my work on http://socket.io/get-started/chat/ . I am working with Sails.js framework which adds its own socket handling method etc.

In config/sockets.js

we have methods onConnect

and onDisconnect

. See https://github.com/balderdashy/sails-docs/blob/master/reference/sails.config/sails.config.sockets.md and (source) https://gist.github.com/Vadorequest/ 568afc14294f1448ab55

I will be comparing sails and socket.io, let's take this code:

io.on('connection', function(socket){
  console.log('a user connected');
  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
});

      

When socket.io is open (connection), it determines listeners

how socket.on('disconnect')

, which are waiting for the selected request, from the client or server using the method socket.emit

.

I thought sails is onConnect

equivalent to socket.io io.on(connection)

. Then the sails method is onDisconnect

equivalent socket.on('disconnect')

, inside io.on(connection)

it will look like a label, suitable for the correct way to handle this particular event and comply with its standards (method starting with on

).

But I showed my code to a friend who was already working with socket.io and sails, and he tells me that I am wrong and what I am doing is defining a listener inside another listener, which will lead to a messy mess (at least) ...

I would like to know if I misunderstood how to set the sails for the sockets.

If I'm wrong, I'll cry, but I'll get over it.

+3


source to share


1 answer


My first impression was really correct, so Sails is hiding the logic socket.io

for us, these two codes are equivalent, the first one uses socket.io

and the second uses Sails config/sockets.js

way:

// Socket.io way
io.on('connection', function(socket){
  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
});

// Sails way (config/sockets.js), hide the socket.io logic. (Facade design pattern)
module.exports.sockets = {
  onDisconnect: function(session, socket) {
    console.log('user disconnected');
  }
}

      



Similarly, the Sails method is onConnect

equivalent to

io.on('connection', function(socket){
    socket.on('connect', function() { 
        console.log('user connected');
     });
});

      

+3


source







All Articles