2012-01-06 6 views
1

GameServer의 새로운 인스턴스를 시작할 때 소켓과 리스너를 다음과 같이 설정합니다.소켓 메시지 (socket.io/node.js)에서 함수 호출하기

var GameServer = function() { 
    this.player = new Player(); 
    var that = this; 

    // Setup sockets and listeners 
    var socket = io.listen(8000); 
    socket.sockets.on('connection', function(client) { 
     client.on('message', that.onSocketMessage); 
     client.on('disconnect', that.onSocketDisconnect); 
    }); 
} 

나는 두 개의 프로토 타입의 GameServer.prototype.onSocketMessage & onSocketDisconnect 있습니다.

내가이 현재 코드에 문제가 : 그 = 이것과 폐쇄를 사용

  1. 를? 기능. 보기 흉한.

  2. onSocketMessage가 호출 될 때, 그 메시지가 GameServer 내에서 다른 함수를 호출한다는 것이 아이디어입니다. 이제 socket.io 시스템에 속하기 때문에 이것이 불가능합니다. 아래를 참조하지 :

...

function onSocketMessage() { 
    this.player.move(); 
} 

this.player이로 더 이상 사용할 수 없습니다. 더 이상 GameServer의 일부가 아닙니다.

소켓 설정과 메시지 전달이 GameServer 함수 및 프로토 타입 외부에서 처리되어야합니까?

또는 어떻게 해결할 수 있습니까?

건배

편집

좋아, 나는 이것을 시도했다, 그래서 그것은 내 생각은 작동하지만 꽤 추한 외모 :

var socket = io.listen(8000); 
socket.sockets.on('connection', function(client) { 
    client.on('message', function (data) { 
     that.onSocketMessage(this, that, data); 
    }); 
    client.on('disconnect', function() { 
     that.onSocketDisconnect(this, that); 
    }); 
}); 

가에 따라 개선 할 수 있습니까?

답변

2

두 가지 점이 도움이 될 수 있습니다. 처음 것 :

this의 기능 시각을 the bind method을 사용하여 수정할 수 있습니다.

socket.sockets.on('connection', function(client) { 
    client.on('message', this.onSocketMessage); 
    client.on('disconnect', this.onSocketDisconnect); 
}.bind(this)); 

기능 끝에는 bind(this)이 호출됩니다. 이 함수는 함수 내부에 this이 무엇이든간에 this이 함수를 벗어나지 않도록 자바 스크립트에 클로저를 생성하도록 지시합니다. (만약 this을 함수 안에 넣고 싶다면, MySomething과 같이 쉽게 bind(MySomething)을 호출 할 수 있습니다. 그러나 bind(this)이 가장 많이 사용됩니다).

것 번째 :

당신은 Socket.IO 소켓에 데이터를 저장할 수 있습니다. 하나의 소켓이 항상 선수와 관련된 경우 Socket.IO 데이터 저장소가 메모리 이외로 설정 될 수 있기 때문에 그래서, 예를 들어, 당신은

socket.set('player', player, function() { 
    // callback is called when variable is successfully stored 
    console.log('player has been stored'); 
}); 

// and later 

socket.get('player', function(err, player) { 
    // callback is called either with an error set or the value you requested 
    player.move(); 
}); 

getset 방법은 콜백을 수행 할 수 있습니다 저장; 예를 들어, Redis.

+0

바인드 옵션이 완벽하게 작동합니다.재미있게도 이미 바인딩을 시도했지만 충분히 잘못 구현했지만 작동하지 않았습니다. 이제 나는 그 이유를 알 수있다! 그래도 질문 : 'client.on ('message ', this.onSocketMessage.bind (this));' 해당 메시지를 받으면 onSocketMessage 내에서 this.id를 사용할 수 있습니다 (클라이언트/소켓 ID) 및 함수에 전달 된 (데이터). 데이터는 계속 전달되지만 this.id에 더 이상 액세스 할 수 없습니다. 내가 어떻게 그것도 통과시킬 수 있을까? –

+0

수 없습니다. 그래서'bind'는 정말로 첫 번째 문제에 유용합니다. 두 번째 문제에 대해서는'player '를 다른 방법으로 가져 오는 작업을 할 것입니다. –

+0

좋습니다! 도와 주셔서 감사합니다. 훌륭한 대답입니다. :) –