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.
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
}
链接地址: http://www.djcxy.com/p/44810.html
上一篇: Ajax推送系统
下一篇: Sailsjs套接字IO