最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - why is socket.id undefined in the browser - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question asked Aug 19, 2015 at 7:41 jack blankjack blank 5,1957 gold badges45 silver badges75 bronze badges 9
  • When I do console.log() in firebug it works as expected. Have you tried that? – slebetman Commented Aug 19, 2015 at 8:35
  • Also, try changing your code to console.log(JSON.stringify(socket)) and I think you'll understand what's happening. – slebetman Commented Aug 19, 2015 at 8:36
  • for console.log(JSON.stringify(socket)) I get TypeError: cyclic object value. Is that what I am supposed to see? – jack blank Commented Aug 19, 2015 at 8:47
  • 4 Hmm. OK. so its not stringifiable. You were supposed to see that the socket object was not yet connected when that console.log() was called. But the reason you can see a connected socket object is that the console displays a live reference of that object so what you're seeing is actually a future version of socket – slebetman Commented Aug 19, 2015 at 9:14
  • 1 To prove this to yourself print socket.id in a setTimeout(). – slebetman Commented Aug 19, 2015 at 9:14
 |  Show 4 more comments

2 Answers 2

Reset to default 16

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)

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);
    });
发布评论

评论列表(0)

  1. 暂无评论