Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 202
Dinesh Avatar asked Dec 16 '13 04:12

Dinesh


1 Answers

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
}
like image 143
iConnor Avatar answered Oct 27 '22 00:10

iConnor