套接字io客户端特定variables

如何将会话特定信息存储在套接字io中?

var client={}; //is this static across all sockets (or connected clients) that are connected? io.on('connection', function(socket){ client.connectiontime=Date.now(); }); //on another io.on('connection') for the same connected client io.on('connection', function(socket){ store(client.connectiontime); } 

如何将客户端variables仅用于与当前连接的客户端相关的操作(如果它被认为是静态的)?

谢谢。

首先,每个套接字都有一个可以用来引用它的名字,但是每当同一个客户端连接时,这个名字就会改变,所以如果在客户端离开之后,这个名字就没有用了。 如果你的目标是把连接时间存储在某个地方(一个数据库?),那么你将不得不从客户端获得一个可以用来再次find它们的唯一标识符,类似于login。 然后,您可以将该date对象传递到处理存储时间的函数中。

你应该注意到,'连接'只在套接字第一次连接时被调用。 连接不是通常在客户端执行某些操作时使用的事件,除非它们在服务器程序的每个访问之间断开连接。

如果您确定只想使用Client对象,则可能必须创build一个客户端数组,然后使用套接字ID作为密钥来访问该对象。 你会有类似的东西

array [socket.id] .connectiontime = Date.now()

 var client={}; //is this static across all sockets (or connected clients) that are connected? var clients = []; io.on('connection', function(socket){ clients[] = { id : socket.id connectiontime : Date.now() } }); //on another io.on('connection') for the same connected client io.on('connection', function(socket){ // Here you would search for the object by socket.id and then store store(client.connectiontime); }