2012-01-06 62 views
1

當我開始遊戲服務器的新實例,它設置了插座和聽衆如下。調用函數(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被調用時,這個想法是它的工作出了什麼消息,然後調用內部遊戲服務器的另一個功能。只有這是不可能的,因爲這屬於socket.io系統。請看下圖:

...

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

this.player不再爲這一點。不再是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

有兩件事可能有幫助。第一件事:

您可以使用the bind method修改功能的願景this

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

通知在函數結束時調用bind(this);這指示JavaScript爲你創建一個閉包,使this在函數外,this在函數內部。 (如果你想使this裏面的功能,比如說,MySomething,你可以很容易地調用bind(MySomething),雖然bind(this)是最常見的用法)。

事情第二:

您可以將數據存儲在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方法採取回調,因爲Socket.IO數據存儲可以被設置爲在內存中的其他東西商店;例如,Redis。

+0

綁定選項完美工作。有趣的是,我已經嘗試綁定,但我實施了不正確的,它沒有工作。現在我明白了爲什麼!雖然問題:'client.on('message',this.onSocketMessage.bind(this));'當收到該消息時,通常在onSocketMessage中,你可以使用this.id(這將是客戶端/套接字ID)和(數據)傳遞給你的函數。數據仍然通過,但我不再有任何訪問this.id.我怎麼會得到這個通過? – 2012-01-06 05:45:12

+0

你不能;這就是爲什麼'bind'對你的第一個問題真的很有用。對於你的第二個問題,我會努力讓'player'以某種方式進入方法。 – 2012-01-06 07:07:08

+0

好的!感謝您的幫助,出色的答案。 :) – 2012-01-06 07:14:20