Sailsjs Socket IO

I am new to SailsJs and Socket IO. I want to execute the below Socket IO example in Sailsjs. In the server side, I need to execute the following code. But I dont know where to place this code.

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) { socket.emit('news', { hello: 'world' }); socket.on('my other event', function (data) { console.log(data); }); });

I am aware that I can place this inside the Cntroller’s function but it will add listener to every request which I dont want.

Client Side:


  var socket = io.connect('http://localhost');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });

Show me where to place the server side code in sailsjs and help me to execute the above socketIO example.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Well, your code is suggesting you want to do something on connection.

There is a file located at /config/sockets.js that has built in functions for connect and disconnect, maybe you are looking for this.

If your not, then you will want to put it into a controller “action”, if you think more deeply about what you are trying to achieve then you will probably need an action that you call once to handle this for you.

If you end up trying out the sockets.js file then you should have something that looks like this

onConnect: function(session, socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
 // By default: do nothing
 // This is a good place to subscribe a new socket to a room, inform other users 
 // that someone new has come online, or any other custom socket.io logic
}

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply