Sailsjs Socket IO

雨燕双飞 提交于 2020-01-01 08:55:48

问题


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:


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
}


来源:https://stackoverflow.com/questions/20603672/sailsjs-socket-io

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!