【问题标题】:Accessing a variable outside of Websocket.onmessage()访问 Websocket.onmessage() 之外的变量
【发布时间】:2013-02-01 18:15:46
【问题描述】:

此问题涉及 NodeJS 中的 WebSocket API(即 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() 传递给我的数据并将其存储在可以在我的游戏中访问的变量中。

【问题讨论】:

    标签: javascript node.js websocket


    【解决方案1】:

    onMessage 作为回调函数被异步触发。因此,您必须注意您正在使用的变量范围。有多种使用可能性:代理、更改的范围、功能、bind() 等,您可以搜索之前的答案。 (有很多)

    作为一个简单的示例,您可能会使用 self 变量在其他地方访问它;但是,这显然取决于整个脚本的用途。

    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));
            };
    };
    

    【讨论】:

      【解决方案2】:

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

      编辑..

      我仍在研究这显然事情正在发展。这个线程解释它link

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-15
        • 2019-05-11
        • 1970-01-01
        • 2020-10-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多