如何用Node.js唯一标识一个套接字 [英] How to uniquely identify a socket with Node.js

查看:149
本文介绍了如何用Node.js唯一标识一个套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TLDR;如何在基于事件的编程模型中识别套接字。



我刚刚开始使用node.js,过去我已经完成了大部分编码
部分在C ++和PHP sockets()中,所以node.js对我来说是非常新颖的东西。



在c ++中,我们可以像编写一个主套接字服务器来侦听新的连接和更改,然后相应地处理这些连接。 解决方案

socket.io,它们确实存在。



但是如前所述,Node.js和Javascript使用基于事件的编程模型,因此您创建了一个(TCP)套接字,listen在一个IP端口上(类似于绑定),然后接受连接事件,它们传递一个表示连接的Javascript对象。

从这里你可以得到FD或其他标识符,但是这个对象也是一个长期存在的对象,如果你愿意的话,你可以存储一个标识符(这就是socke t.io)。

  var server = net.createServer(); 
$ b 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);


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.

解决方案

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

这篇关于如何用Node.js唯一标识一个套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆