开发者

node.js & socket.io using client specific variables

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

  var player = 0;
  client.on('message',f开发者_开发百科unction(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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜