【发布时间】:2014-02-18 18:11:19
【问题描述】:
我正在为 node.js 使用这个简单的 WebSockets 实现 https://npmjs.org/package/ws
想知道服务器上的变量是否默认是用户或服务器特定的......?我无法理解许多用户和一台服务器......节点现在看起来就像薛定谔的猫(它既是又不是)
如果我设置服务器:
var thing=(thing>0)?thing:0;
console.log('thing='+thing+' this only seems to happen when the server born, hmm ok...');
//Normal require/set up ws stuff...
wss.on('connection',function(ws){
thing=Math.floor(Math.random()*101);
ws.on('message',function(_){
ws.send('reply: thing='+thing);
});
});
还有客户:
ws=new WebSocket('ws://'+somehost+':'+(someport));
ws.onopen=function(){
ws.onmessage=function(_){console.log(_.data);}
ws.send('question: what is the thing now?');
}
$('#button').click(function(){ws.send('question: what is the thing now?');});
现在如果我有两个用户(A 和 B)一个接一个地访问网站:
用户 A 将打开页面并将 var 视为第一个随机数
用户 B 将其视为第二个随机数
A 可以点击按钮,然后将其视为第二个随机数
如果 B 点击按钮 B 也会看到第二个随机数
...因为B在服务器上给大家改了?
我这样做对吗?要在服务器上创建一个特定于连接的变量没有来自客户端的(零)有用信息?
如果我不清楚我想做的是 A 总是看到它设置的数字,而 B 总是看到它设置的数字。
服务器可以/是否知道区别?
只是将代码放在哪里的问题吗? (如示例仅在服务器诞生时显示控制台日志)
或者它是否类似于 Javascript 复制对象与引用对象之间的区别?
【问题讨论】: