Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 访问Websocket.onmessage()之外的变量_Javascript_Node.js_Websocket - Fatal编程技术网

Javascript 访问Websocket.onmessage()之外的变量

Javascript 访问Websocket.onmessage()之外的变量,javascript,node.js,websocket,Javascript,Node.js,Websocket,这个问题涉及NodeJS中的websocketapi(即var webSocketServer=require('WebSocket').server;) function Game(canvas) { this.wArray; this.runConnection(); // I want to be able to see changes in variables at this point console.log(this.wArray[1][2]); //

这个问题涉及NodeJS中的websocketapi(即var webSocketServer=require('WebSocket').server;)

function Game(canvas) {
    this.wArray;
    this.runConnection();
    // I want to be able to see changes in variables at this point
    console.log(this.wArray[1][2]); // is out of scope or something
}

_p = Game.prototype;

_p.runConnection = function() {
    this.connection = new WebSocket('ws://localhost:1337');
    this.connection.onmessage = function (message) {
           this.wArray = JSON.parse(message.data);
    };
    // code here runs before code inside onmessage, it must be asychronous
};
因此,当我收到来自服务器的消息时,我应该能够接收该消息并更新代码中的一些变量。目前,我所能做的似乎就是更新onmessage函数内部的内容。所有在线示例都简单地展示了人们在onmessage中使用console.log()。我希望服务器能够发送我的客户端信息,然后在游戏运行时使用这些信息更新游戏的某些方面。我认为onmessage()有一定程度的不同步性


请告诉我如何获取通过WebSocket.onmessage()传递给我的数据,并将其存储在可以在整个游戏中访问的变量中

我建议看一下now.js,它允许客户端和服务器在同一名称空间中运行,这允许两端共享内容

编辑


我仍在研究这一点,显然事情正在进展。此线程解释了onMessage作为回调函数异步启动的原因。因此,您必须注意您工作的可变范围。可以使用多种方法:代理、更改的作用域、函数、
bind()
,等等,您可以搜索先前的答案。(有很多)

举个简单的例子,您可以使用一个自变量在其他地方访问它;然而,这显然取决于整个脚本的目的

function Game(canvas) {
    this.wArray = [];
    this.runConnection();
    console.log(this.wArray[1][2]); 
   //log()  will likely not work as you should wait for [1][2] to be filled
}

_p = new Game();

_p.runConnection = function() {
    this.connection = new WebSocket('ws://localhost:1337');
    var self = this;
    this.connection.onmessage = function (message) {
           self.wArray.push(JSON.parse(message.data));
        };
};