Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is socket.id undefined in the browser

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.

like image 878
jack blank Avatar asked Aug 19 '15 07:08

jack blank


People also ask

How do I get a Socket id?

socket.id can be obtained after 'connect' event. Note, the socket.id on the server is not made available to the client, so if you want the id from the server, then you can send it to the client yourself in a message.

How do I send a Socket id?

You can try the code below:io.to(socket.id). emit("event", data); whenever a user joined to the server, socket details will be generated including ID. This is the ID really helps to send a message to particular people.


2 Answers

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)

like image 114
Oleg Avatar answered Sep 28 '22 07:09

Oleg


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);
    });
like image 26
thegreytangent Avatar answered Sep 28 '22 06:09

thegreytangent