How unique is socket.id?

后端 未结 2 1399
暖寄归人
暖寄归人 2021-01-12 02:23

I\'m building an application where I\'d like a unique identifier for every connection for the duration that the app is running and I\'m wondering if socket.id works for this

相关标签:
2条回答
  • 2021-01-12 02:42

    Looking at socket.io's code, it seems that the id of a user uniquely identifies a socket client. See, for example, the code for Socket.connect:

    Socket.prototype.onconnect = function(){
      debug('socket connected - writing packet');
      this.join(this.id);
      this.packet({ type: parser.CONNECT });
      this.nsp.connected[this.id] = this;
    };
    

    On the last line, the id is used in a hash that keeps track of connected sockets. Since you need your ids to be unique, each id is then unique as long as the server has not been restarted

    0 讨论(0)
  • 2021-01-12 02:47

    Assuming that you're using socket.io@0.9.x (which is the present version in NPM), the code that generates a new id for each connection/client can be found here.

    I think that you can safely assume that each socket id is going to be unique.

    0 讨论(0)
提交回复
热议问题