9
votes

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.

1
The sails.js implementation routes all of its socket.io requests through the express.js interface actually. Have a look here to read about how to implement sockets with Sails; while they do also support the native Socket.io controls, that's probably not the best place to start.brandonscript
@r3mus I agree.I just need to know where to run this Native SOCKET.IO server code inside sailsjs. Thanks for your reply. Appreciated.Dinesh
I'd go through and build a basic sails project and look through the code to see where sockets are configured; TBH I haven't actually done any non-standard socket stuff with Sails yet.brandonscript
Yes. To the best of my knowledge.. This accessing native socket.io stuffs in sails is not documented well in internet. it should help guys like me.. :-)Dinesh

1 Answers

8
votes

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
}