why is socket.id undefined in the browser

2020-08-23 00:56发布

问题:

If i do console.log(socket) i get a socket object in firebug. In the obj I could see a property with id and i could see the value of the id. But when I do console.log(socket.id) i get undefined. why?

   var socket = io();
    $(document).ready( function(){
        console.log(socket);
        console.log(socket.id);
        console.log(socket.ids);
        $(".click").on("click", function(e){
            alert("clicked")
            socket.emit("clicked", socket.id)
            $(this).addClass("removeclick");
        })
     });

ps I could get socket.ids which is 0 but not socket.id.

回答1:

Socket.io needs some time for establish the connection. The best way I found to get ID on client-side is:

socket.on('connect', () => {console.log(socket.id)});

'connect' is system event which emitting when connection is ready.

(my current socket.io version is 1.7.2)



回答2:

set the port Lister and get the id via anonymous function 'http://localhost:8000'

this.socket = io('http://localhost:8000');
    this.socket.on('connect' , () => {
      console.log(this.socket.id);
    });