Html 如何使用 Node.js 唯一标识套接字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6805432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 09:42:54  来源:igfitidea点击:

How to uniquely identify a socket with Node.js

htmlnode.jssockets

提问by ShrekOverflow

TLDR; How to identify sockets in event based programming model.

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

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.

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

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.

在 C++ 中,我们可以做一些事情来识别套接字,比如编写一个主套接字说服务器来监听新的连接和更改,然后相应地处理这些连接。

回答by Timothy Meade

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

如果您正在寻找实际的套接字而不是 socket.io,它们确实存在。

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.

但如前所述,Node.js 和 Javascript 使用基于事件的编程模型,因此您创建一个 (TCP) 套接字,侦听 IP:port(类似于绑定),然后接受传递表示连接的 Javascript 对象的连接事件.

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

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

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

回答by ecdeveloper

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:

Timothy 的方法很好,唯一值得一提的是 - Math.random() 可能会导致 id 的重复。所以它产生相同随机数的机会真的很小,但它可能会发生。所以我建议你使用 dylang 的模块 - 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.

因此,在这种情况下,您可以确保不会发生 id 重复。

回答by low_rents

if you found this question by looking for socket.iounique ids that you can use to differentiate between sockets on the client-side (just like i did), then here is a very simple answer:

如果您通过查找socket.io可用于区分客户端套接字的唯一 ID(就像我所做的那样)发现了这个问题,那么这里有一个非常简单的答案:

var id = 0; //initial id value
io.sockets.on('connection', function(socket) {

    var my_id = id; //my_id = value for this exact socket connection
    id++; //increment global id for further connnections

    socket.broadcast.emit("user_connected", "user with id " + my_id + "connected");
}

on every new connection the idis incremented on the serverside. this guarantees a unique id.
I use this method for finding out where a broadcast came from on the clientside and saving data from concurrent sockets.

在每个新连接id上,服务器端都会增加。这保证了唯一的 id。
我使用这种方法来找出广播来自客户端的位置并保存来自并发套接字的数据。

for example:

例如:

server-side

服务器端

var my_coords = {x : 2, y : -5};
socket.broadcast.emit("user_position", {id: my_id, coord: my_coords});  


client-side


客户端

user = {};
socketio.on("user_position", function(data) {
    if(typeof user[data.id] === "undefined")
        user[data.id] = {};

    user[data.id]["x"] = data.coord.x;
    user[data.id]["y"] = data.coord.y;
});

回答by jumper rbk

How to identify a client based on its socket id. Useful for private messaging and other stuff.

如何根据套接字 ID 识别客户端。对私人消息和其他东西很有用。

Using socket.io v1.4.5

使用 socket.io v1.4.5

client side:

客户端:

var socketclientid = "john"; //should be the unique login id
var iosocket = io.connect("http://localhost:5000", {query: "name=john"});

var socketmsg = JSON.stringify({
  type: "private messaging",
  to: "doe",
  message: "whats up!"
});                        
iosocket.send(socketmsg);

server side:

服务器端:

io.on('connection', function(socket){
  var sessionid = socket.id;
  var name = socket.handshake.query['name'];
  //store both data in json object and put in array or something

socket.on('message', function(msg){
  var thesessionid = socket.id;      
  var name = ???? //do lookup in the user array using the sessionid
  console.log("Message receive from: " + name);

  var msgobject = JSON.parse(msg);
  var msgtype = msgobject.type;
  var msgto = msgobject.to;
  var themessage = msgobject.message;

  //do something with the msg
  //john want to send private msg to doe
  var doesocketid = ???? //use socket id lookup for msgto in the array
                         //doe must be online
  //send to doe only
  if (msgtype == "private messaging") 
     socket.to(doesocketid).emit('message', 'themessage');

});

回答by pkyeck

mmmm, i don't really get what you're looking for but socket-programming with node.js (and socket.io) is really straight forward. take a look at some examples on the socket.io homepage:

嗯,我真的不明白你在找什么,但是使用 node.js(和 socket.io)进行套接字编程真的很简单。看看socket.io 主页上的一些例子:

// note, io.listen() will create a http server for you
var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
  io.sockets.emit('this', { will: 'be received by everyone connected'});

  socket.on('private message', function (from, msg) {
    console.log('I received a private message by ', from, ' saying ', msg);
  });

  socket.on('disconnect', function () {
    sockets.emit('user disconnected');
  });
});

on connecting to the server, every socket get an unique id with which you can identify it later on.

在连接到服务器时,每个套接字都会获得一个唯一的 ID,您可以稍后使用它来识别它。

hope this helps!? cheers

希望这可以帮助!?干杯

回答by Alfred

In c++ to identify a socket we could have done something like writing a main socket say server to listen for new connections and then handling those connections accordingly.but so far i havent found anything like that in node.js . (the berkeley socket model) Does it even exist in node.js .. if not i am going back to my C++ :$

在 C++ 中,我们可以做一些事情来识别一个套接字,比如编写一个主套接字说 server 来侦听新连接,然后相应地处理这些连接。但到目前为止,我还没有在 node.js 中找到类似的东西。(伯克利套接字模型)它是否存在于 node.js .. 如果不是,我将回到我的 C++ :$

You should go back, because JavaScript is a prototype-based, object-oriented scripting language that is dynamic, weakly typed and has first-class functions.They are both completely different languages and you will have to have a different mindset to write clean JavaScript code.

你应该回去,因为JavaScript 是一种基于原型、面向对象的脚本语言,它是动态的、弱类型的并且具有一流的功能。它们都是完全不同的语言,你必须有不同的心态来编写干净的 JavaScript 代码。

https://github.com/LearnBoost/Socket.IO/wiki/Migrating-0.6-to-0.7

https://github.com/LearnBoost/Socket.IO/wiki/Migrating-0.6-to-0.7

Session ID

If you made use of the sessionId property of socket in v0.6, this is now simply .id.

// v0.6.x
var sid = socket.sessionId;

// v0.7.x
var sid = socket.id;

会话 ID

如果您在 v0.6 中使用了 socket 的 sessionId 属性,现在它只是.id。

// v0.6.x
var sid = socket.sessionId;

// v0.7.x
var sid = socket.id;