Calling functions on socket message (

When I start a new instance of GameServer, it sets up the socket and listeners as follows.

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

I then have two prototypes GameServer.prototype.onSocketMessage & onSocketDisconnect.

I have two problems with the current code:

  1. Using that = this and the closure? function. Looks ugly.

  2. When onSocketMessage is called, the idea is it works out what the message is then calls another function within GameServer. Only this isn’t possible as now this belongs to the system. See below:

function onSocketMessage() {

this.player is no longer available as this. is no longer part of GameServer.

Should my socket setup and message passing be handled outside of GameServer function and prototypes?

Or how else could I resolve this?



Ok so I have tried this and it works but looks pretty ugly I think:

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

Can it be improved upon?

Problem courtesy of: Chris Evans


Two things that may help. Thing the first:

You can modify a function’s vision of this
the bind


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

Notice the call to bind(this)
at the end of the function; this instructs JavaScript to create a closure for you, making whatever this
is outside the function, this
inside the function. (If you wanted to make this
inside the function, say, MySomething
, you could just as easily call bind(MySomething)
, though bind(this)
is the most common use).

Thing the second:

You can store data in a Socket.IO socket. So, for example, if one socket is always associated with a player, you can do

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

The get
and set
methods take callbacks because the Socket.IO data store can be set to something other than an in-memory store; for example, Redis.

Solution courtesy of: Michelle Tilley

Node.js Recipes责编内容来自:Node.js Recipes (源链) | 更多关于

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » Calling functions on socket message (

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录