How to uniquely identify a socket with Node.js

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

    If you are looking for actual sockets and not socket.io, they do exist.

    But as stated, Node.js and Javascript use an event-based programming model, so you create a (TCP) socket, listen on an IP:port (similar to bind), then accept connection events which pass a Javascript object representing the connection.

    From this you can get the FD or another identifier, but this object is also a long-lived object that you can store an identifier on if you wish (this is what socket.io does).

    var server = net.createServer();
    
    server.on('connection', function(conn) {
      conn.id = Math.floor(Math.random() * 1000);
      conn.on('data', function(data) {
        conn.write('ID: '+conn.id);
      });
    });
    server.listen(3000);
    

提交回复
热议问题