How to uniquely identify a socket with Node.js

后端 未结 7 1859
时光说笑
时光说笑 2020-12-10 01:25

TLDR; How to identify sockets in event based programming model.

I am just starting up with node.js , in the past i have done most of my coding part in C++ and PHP s

7条回答
  •  天命终不由人
    2020-12-10 02:16

    How to identify a client based on its socket id. Useful for private messaging and other stuff.

    Using socket.io v1.4.5

    client side:

    var socketclientid = "john"; //should be the unique login id
    var iosocket = io.connect("http://localhost:5000", {query: "name=john"});
    
    var socketmsg = JSON.stringify({
      type: "private messaging",
      to: "doe",
      message: "whats up!"
    });                        
    iosocket.send(socketmsg);
    

    server side:

    io.on('connection', function(socket){
      var sessionid = socket.id;
      var name = socket.handshake.query['name'];
      //store both data in json object and put in array or something
    
    socket.on('message', function(msg){
      var thesessionid = socket.id;      
      var name = ???? //do lookup in the user array using the sessionid
      console.log("Message receive from: " + name);
    
      var msgobject = JSON.parse(msg);
      var msgtype = msgobject.type;
      var msgto = msgobject.to;
      var themessage = msgobject.message;
    
      //do something with the msg
      //john want to send private msg to doe
      var doesocketid = ???? //use socket id lookup for msgto in the array
                             //doe must be online
      //send to doe only
      if (msgtype == "private messaging") 
         socket.to(doesocketid).emit('message', 'themessage');
    
    });
    

提交回复
热议问题