2013-02-01 2 views
1

이 질문은 NodeSS의 WebSocket API (예 : var webSocketServer = require ('websocket'). server;)와 관련이 있습니다.WebSocket.onmessage() 외부 변수 액세스하기

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()를 통해 나에게 전달 된 데이터를 가져와 내 게임에서 액세스 할 수있는 변수에 저장하는 방법을 보여주십시오.

답변

0

클라이언트와 서버가 동일한 네임 스페이스에서 작동 할 수 있도록 now.js를 살펴 보는 것이 좋습니다. 이렇게하면 양쪽 끝에서 물건을 공유 할 수 있습니다.

편집 ..

나는 아직도 이것에 대해 연구 중이다. 이 스레드는 설명합니다 link

0

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)); 
     }; 
}; 
관련 문제