节点.js & socket.io 使用客户端特定变量

发布于 2024-10-16 05:49:52 字数 404 浏览 3 评论 0原文

socket.on('connection', function(client){ 
    var clientid = client.sessionId;
  console.log('Connection from '+clientid);

  var player = 0;
  client.on('message',function(data){ 
    HandleClientData(data,clientid);
  });
  client.on('disconnect',function(){
    console.log('Server has disconnected');
  });  
});

变量“player”对于客户端来说是唯一的吗? 如何从另一个函数获取/设置此变量?

谢谢。

socket.on('connection', function(client){ 
    var clientid = client.sessionId;
  console.log('Connection from '+clientid);

  var player = 0;
  client.on('message',function(data){ 
    HandleClientData(data,clientid);
  });
  client.on('disconnect',function(){
    console.log('Server has disconnected');
  });  
});

Is the variable "player" unique to the client?
How can I get/set this variable from another function?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

救赎№ 2024-10-23 05:49:53

它是建立套接字连接时运行的匿名函数的本地变量。如果您想从另一个函数读取它,请将其移至全局范围或将其作为参数之一传递到该函数中。如果您想从另一个函数设置它,请将其移至全局范围或将其传递到该函数并在该函数返回时读取其值。

如果您解释一下要使用 player 做什么,可能会有更清晰的答案。

It's a variable local to the anonymous function that runs when a socket connection is established. If you want to read it from another function, either move it into the global scope or pass it into that function as one of its arguments. If you want to set it from another function, either move it to the global scope or pass it into that function and read its value when that function returns.

If you explain what you want to use player for, there's probably a much clearer answer.

腻橙味 2024-10-23 05:49:53

怎么样:

socket.on('connection', function(client){
client.player = 0;
console.log('Connection from '+client.clientid);

client.on('message',function(data){
    someOtherFunctions(this.player); 
    HandleClientData(data,this.clientid);
});
client.on('disconnect',function(){
  console.log(this.clientid+' has been disconnected');
  });  
});

您可以为连接的套接字单独定义任何数据,并在具有“this”范围的其他回调中使用它们。 “this”指的是当前套接字

what about this:

socket.on('connection', function(client){
client.player = 0;
console.log('Connection from '+client.clientid);

client.on('message',function(data){
    someOtherFunctions(this.player); 
    HandleClientData(data,this.clientid);
});
client.on('disconnect',function(){
  console.log(this.clientid+' has been disconnected');
  });  
});

You can define any data individually for the connected sockets and use them in other callbacks with "this" scope. "this" refers to the current socket

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文