Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 sockets() so node.js is something extremely new to me.

In c++ to identify a socket we could have done something like writing a main socket say server to listen for new connections and changes, and then handling those connections accordingly.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
521 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...