How to uniquely identify a socket with Node.js

后端 未结 7 1886
时光说笑
时光说笑 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:27

    Timothy's approach is good, the only thing to mention - Math.random() may cause id's duplication. So the chance it will generate the same random number is really tiny, but it could happen. So I'd recommend you to use dylang's module - shortid:

    var shortid = require('shortid');
    var server = net.createServer();
    
    server.on('connection', function(conn) {
      conn.id = shortid.generate();
      conn.on('data', function(data) {
        conn.write('ID: '+conn.id);
      });
    });
    server.listen(3000);
    

    So in that case you can be sure that no id duplications will occur.

提交回复
热议问题