且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用socketio实时显示在线/离线用户使用Sails?

更新时间:2023-12-02 15:48:28

@InternalFX发布了一个不错的方法;您可以在Sails v0.10.x上使用的替代方法是:

@InternalFX posted a good method; an alternative that you can use on Sails v0.10.x would be:

  onConnect: function(session, socket) {

    // If this is a logged in user, subscribe the socket to a 
    // custom "loggedInCount" room
    if (session.user) {
      var roomName = 'loggedIn'+session.user.id;
      sails.sockets.join(socket, roomName);
      // If this is the first subscriber, the user is just coming online, 
      // so notify any subscribers about the state change.
      if (sails.sockets.subscribers(roomName).length == 1) {
        User.message(session.user.id, {state: 'online'}, socket);
      }
    }

  },

  onDisconnect: function(session, socket) {

    if (session.user) {
      var roomName = 'loggedIn'+session.user.id;
      sails.sockets.leave(socket, roomName);
      // If this was the last subscriber, the user is going offline, 
      // so notify any subscribers about the state change.
      if (sails.sockets.subscribers(roomName).length == 0) {
        User.message(session.user.id, {state: 'offline'}, socket);
      }
    }

  },

这使用Sails的内置pubsub架构,在特定用户上线或下线时通知连接的套接字。它需要套接字来订阅他们想要了解的用户实例(在客户端上使用类似 socket.get('/ user')的东西),这是一个很好的做法进入。这样,您只会收到有关您关注的用户的通知(例如,如果您有朋友列表)。

This uses Sails' built-in pubsub architecture to notify connected sockets whenever a particular user comes online or goes offline. It requires sockets to subscribe to the user instances they want to know about (using something like socket.get('/user') on the client), which is a good practice to get into. This way you can be notified only about the users you care about (e.g. if you had a "friends list").