Getting UID from socket.io event & managing events

NodeBB Plugins
  • What would be the best way to get the UID of the a socket that emitted an event,
    EX:
    sockets.server.on('SomeEvent', function(data) {
           console.log('UID of socket who sent/called that event');
    });

    On top of that, I'm having trouble listening to events in socket.io, as I'm used to setting up socket.io, and not having pre-setup functions and what not. I'm used to being able to do:
    io.on('connection', function(socket) {
           //Socket events here
    });

    but instead I'm supposed to work with sockets.server? How would one go about setting up/listening to events for this?

  • When you add a listener to one of the modules ('admin', 'categories', 'groups', 'meta', 'modules', 'notifications', 'plugins', 'posts', 'topics', 'user'), additional data is verified and sent.

    var socketPlugins = module.parent.require('./socket.io/plugins')
    
    socketPlugins.yourplugin = {
    
      // This function is now exposed as the event 'plugins.yourplugin.someevent'
      someevent: function (socket, data, callback) {
    
        // socket.uid is now the verified uid of the user sending the event.
        // data is the object sent with the event.
        console.log("UID " + socket.uid + " sent data:", data);
    
        // socket.uid is 0 if the user is a guest.
        callback(!socket.uid, {uid: socket.uid});
      }
    }
    

    client

    socket.emit('plugins.yourplugin.someevent', {somedata: 'somevalue'}, function (err, data) {
      if (!err) console.log("You are UID " + data.uid);
    });
    
  • I see! Thanks! Is there a Doc for this? I haven't had luck finding anything

  • @Stackoverload

    I don't think so. I think I just discovered it by examining other plugins and the core code.

  • @yariplus Ahh, I should do such! Thanks 😄

  • This would be an excellent addition to our documentation 🙂


Suggested Topics