如何在风帆控制器中获取当前的套接字对象或 ID? [英] How to get current socket object or id with in a sails controller?

查看:22
本文介绍了如何在风帆控制器中获取当前的套接字对象或 ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 sails.js (v0.12 ) 控制器函数中访问当前连接的套接字 ID.sails.sockets.getId(req.socket);显示未定义,因为这不是套接字请求

I would like to access the currently connected socket id with in a sails.js (v0.12 ) controller function. sails.sockets.getId(req.socket); is showing undefined since this is not a socket request

我的目的是设置我的用户登录成功后在数据库中的在线状态

My objective is to set the online status of my user in the database when he logged in successfully

login: function (req, res) {

    Util.login(req, function(){
        var socketId = sails.sockets.getId(req.socket);
        console.log('socketId ===', socketId); // return undefined
    });
},

基本上我想在控制器中访问当前用户的套接字对象或使用 socket on 方法

Basically i would like to access the current user's socket object in a controller or access current user's session object with in a socket on method

此外,我不确定如何重写旧的 sockets.onConnect处理程序

Also i'm not sure that how can i rewrite my old sockets.onConnect handler

 onConnect: function(session, socket) {
// Proceed only if the user is logged in

if (session.me) {
    //console.log('test',session);

    User.findOne({id: session.me}).exec(function(err, user) {
        var socketId = sails.sockets.getId(socket);

        user.status = 'online';
        user.ip = socket.handshake.address;

        user.save(function(err) {
          // Publish this user creation event to every socket watching the User model via User.watch()
          User.publishCreate(user, socket);
        });

        // Create the session.users hash if it doesn't exist already
        session.users = session.users || {};

        // Save this user in the session, indexed by their socket ID.
        // This way we can look the user up by socket ID later.
        session.users[socketId] = user;

        // Persist the session
        //session.save();

        // Get updates about users being created
        User.watch(socket);

        // Send a message to the client with information about the new user
        sails.sockets.broadcast(socketId, 'user', {
          verb :'list',
          data:session.users
        });
    });
}
},

推荐答案

您需要将 req 对象传递给方法.

You need to pass the req object to the method.

if (req.isSocket) {
    let socketId = sails.sockets.getId(req);
    sails.log('socket id: ' + socketId);
}

由于请求不是套接字请求,您可能需要执行类似的操作

Since the request is not a socket request, you might need to do something like

  • 登录后向客户端发送回一些标识符.
  • 使用标识符加入房间.(每个房间一名用户.)
  • 每当您需要向客户端发送消息时,向带有标识符的房间广播消息.

https://gist.github.com/crtr0/2896891

更新:

来自sails 迁移指南

onConnect 生命周期回调已被弃用.相反,如果您需要在连接新套接字时执行某些操作,请从新连接的客户端发送请求以执行此操作.onConnect 的目的始终是优化性能(消除与服务器进行初始额外往返的需要),但它的使用可能会导致混乱和竞争条件.如果您迫切需要消除服务器往返,您可以直接在 bootstrap 函数 (config/bootstrap.js) 中的 Sails.io.on('connect', function (newlyConnectedSocket){}) 上绑定处理程序.但是,请注意,这是不鼓励的.除非您面临真正的生产性能问题,否则您应该将上述策略用于连接时"逻辑(即在套接字连接后从客户端发送初始请求).套接字请求是轻量级的,因此不会给您的应用程序增加任何有形的开销,而且有助于使您的代码更具可预测性.

The onConnect lifecycle callback has been deprecated. Instead, if you need to do something when a new socket is connected, send a request from the newly-connected client to do so. The purpose of onConnect was always for optimizing performance (eliminating the need to do this initial extra round-trip with the server), yet its use can lead to confusion and race conditions. If you desperately need to eliminate the server roundtrip, you can bind a handler directly on sails.io.on('connect', function (newlyConnectedSocket){}) in your bootstrap function (config/bootstrap.js). However, note that this is discouraged. Unless you're facing true production performance issues, you should use the strategy mentioned above for your "on connection" logic (i.e. send an initial request from the client after the socket connects). Socket requests are lightweight, so this doesn't add any tangible overhead to your application, and it will help make your code more predictable.

// in some controller
if (req.isSocket) {
    let handshake = req.socket.manager.handshaken[sails.sockets.getId(req)];
    if (handshake) {
        session = handshake.session;
    }
}

这篇关于如何在风帆控制器中获取当前的套接字对象或 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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