Show the connecting user login status using Websocket and Pusher

假装没事ソ 提交于 2019-12-06 10:48:15

You don't need a separate channel in order to build user status.

The best way to achieve this right now would be to detect user status using something like idle.js and then trigger an event on the presence channel (maybe client-status-updated) with information about the user status (e.g. {"user_id":SOME_ID, "status":"away"}).

Note: for client events the client- prefix is required on the event name

You can do this using client events and this can be done on the existing existing presence channels. However, you should be aware that by using client events it means any authenticated user could potentially trigger a status event and suggest it is for another user altogether. So, it would be more secure to do this via the server that can set the even it coming from the user who's status is being set.

However, I don't really see the benefit of the "hack" to set another user's status.

Here's an example using the presence channel and client events.

<script src="libs/idle.js"></script>
<script src="//js.pusher.com/2.2/pusher.min.js"></script>
<script>
var pusher = new Pusher(APP_KEY);
var presence = pusher.subscribe('presence-online');

// Basic online/offline
presence.bind('pusher:subscription_succeeded', function(members) {
  members.each(addUser);
});

presence.bind('pusher:member_added', addUser);
presence.bind('pusher:member_removed' removeUser);

function addUser(member) {
  // Online - add to UI
}

function removeUser(member) {
  // Offline - remove from UI
  // Consider doing this in a setTimeout
  // in case the user comes back online again
}

// User state
var idle = new Idle({
  onHidden:    function() { sendUserStatus('hidden'); },
  onVisible:   function() { sendUserStatus('visible'); },
  onAway:      function() { sendUserStatus('away'); },
  onAwayBack:  function() { sendUserStatus('hidden'); },
  awayTimeout: 30000 //away with 30 seconds of inactivity
}).start();

function sendUserStatus(status) {
  var userStatusUpdate = {
    "user_id": presence.members.me.id, // current user unique ID
    "status": status
  };
  presence.trigger('client-status-updated', userStatusUpdate);
}

presence.bind('client-status-updated', function(update) {
  var userId = update.user_id;
  var status = user.status;
  // Update UI to reflect user status
});
</script>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!