Sailsjs 套接字 IO [英] Sailsjs Socket IO

查看:39
本文介绍了Sailsjs 套接字 IO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 SailsJs 和 Socket IO 的新手.我想在 Sailsjs 中执行下面的 Socket IO 示例.在服务器端,我需要执行以下代码.但我不知道把这段代码放在哪里.

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

io.sockets.on('connection', function (socket) {socket.emit('news', { 你好: 'world' });socket.on('我的另一个事件',函数(数据){控制台日志(数据);});});


我知道我可以将它放在 Ctrl 的函数中,但它会为我不想要的每个请求添加侦听器.

客户端:

<前>var socket = io.connect('http://localhost');socket.on('news', function (data) {控制台日志(数据);socket.emit('我的另一个事件', { my: 'data' });});

告诉我在哪里放置sailsjs中的服务器端代码并​​帮助我执行上面的socketIO示例.

解决方案

好吧,你的代码暗示你想要在 connection 上做一些事情.

/config/sockets.js 中有一个文件,它内置了 connectdisconnect 的函数,也许你正在寻找为了这.

如果不是,那么您将希望将其放入控制器 action",如果您更深入地考虑要实现的目标,那么您可能需要一个您调用的操作一次为您处理.

如果你最终尝试了 sockets.js 文件,那么你应该有这样的东西

onConnect:函数(会话,套接字){socket.emit('news', { 你好: 'world' });socket.on('我的另一个事件',函数(数据){控制台日志(数据);});//默认情况下:什么都不做//这是一个为房间订阅新套接字的好地方,通知其他用户//新人上线,或任何其他自定义 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
}

这篇关于Sailsjs 套接字 IO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆