Sending a message to a client via its socket.id

前端 未结 2 968
清酒与你
清酒与你 2020-12-04 11:47

I can only seem emit messages to users when their socket id has been directly stored within the io.sockets.on(\'connect\') function. I don\'t know why it doesn\'t work when

2条回答
  •  暖寄归人
    2020-12-04 12:22

    I can see that this post is generating quite a lot of interest... so i'm going to post the code I used to implement this:

    Notes

    I have used Redis as the session storage. The session is initially setup during the login page via a HTTP request containing the users details, if these details are valid (Checked against a MongoDB document)... then the session is created.

    Server Side Code Creation and Removal of Session / Socket

    //Auth the user
    io.set('authorization', function (data, accept) {
      // check if there's a cookie header
      if (data.headers.cookie) {
        data.cookie = parseCookie(data.headers.cookie);
        data.sessionID = data.cookie['express.sid'];
    
        //Save the session store to the data object
        data.sessionStore = sessionStore;
    
        sessionStore.get(data.sessionID, function(err, session){
          if(err) throw err;
    
          if(!session)
          {
            console.error("Error whilst authorizing websocket handshake");
            accept('Error', false);
          }
          else
          {
            console.log("AUTH USERNAME: " + session.username);
            if(session.username){
              data.session = new Session(data, session);
              accept(null, true);
            }else {
              accept('Invalid User', false);
            }
          }
        })
      } else {
        console.error("No cookie was found whilst authorizing websocket handshake");
        return accept('No cookie transmitted.', false);
      }
    });
    
    /** A new socket connection has been accepted */
    io.sockets.on('connection', function (socket)
    {    
      var hs = socket.handshake;
      if(hs.session)
      {
        if(hs.session.username)
        {
            clients[socket.id] = socket; // add the client data to the hash
            validUsers[hs.session.username] = socket.id; // connected user with its socket.id
        }
      }
    
    
      socket.on('disconnect', function()
      {
        delete browsing[hs.session.username]; //Remove the client from the browsing hash
        delete clients[socket.id];         // remove the client from the array
        delete validUsers[hs.session.username]; // remove connected user & socket.id
      })
    ....
    }
    

    Server Side Selective Message Sending

    This code allows me to send a message to team members of a project. A team of users won't receive messages from a separate team of users..

    for(var i = 0; i < project.team.length; i++)
    {
      if(validUsers[project.team[i].username])
      {
        if(clients[validUsers[project.team[i].username]])
        {
          projects.update({"_id" : projectId},
            {"$pull" :
              {"stories" : {"_id" :  storyId}}
            }
          );                
          clients[validUsers[project.team[i].username]].emit('delete-story', storyId); 
        }
        else
        {
          console.error("Project team member not found");
        }
      }
    }
    

提交回复
热议问题