【问题标题】:Node.js + socket.io using socket object in a modelNode.js + socket.io 在模型中使用套接字对象
【发布时间】:2016-02-15 15:19:11
【问题描述】:

为什么我会收到这条消息?

我的 app.js

io.sockets.on('connection', function(socket) {
    socket.on('login', function(data) {
        var player = new Player(socket, name)
    })      
}) 

我的 player.js

var Player = function(socket, name) {
    this.socket = socket
    this.name_ = name
};

我无法解决这个问题,我不知道如何解决这个问题。这是一个问题吗?

错误信息:

缺少错误处理程序 onsocket。 RangeError:最大调用堆栈大小 _hasBinary 的 Object.hasOwnProperty (native) 超出 (/Users/macbook/Desktop/batak/node_modules/socket.io/node_modules/has-binary/index.js:49:45) 在 _hasBinary (/Users/macbook/Desktop/batak/node_modules/socket.io/node_modules/has-binary/index.js:49:63) 在 _hasBinary (/Users/macbook/Desktop/batak/node_modules/socket.io/node_modules/has-binary/index.js:49:63) 在 _hasBinary (/Users/macbook/Desktop/batak/node_modules/socket.io/node_modules/has-binary/index.js:49:63) 在 _hasBinary (/Users/macbook/Desktop/batak/node_modules/socket.io/node_modules/has-binary/index.js:49:63) 在 _hasBinary (/Users/macbook/Desktop/batak/node_modules/socket.io/node_modules/has-binary/index.js:49:63) 在 _hasBinary (/Users/macbook/Desktop/batak/node_modules/socket.io/node_modules/has-binary/index.js:49:63) 在 _hasBinary (/Users/macbook/Desktop/batak/node_modules/socket.io/node_modules/has-binary/index.js:49:63) 在 _hasBinary (/Users/macbook/Desktop/batak/node_modules/socket.io/node_modules/has-binary/index.js:49:63)

【问题讨论】:

  • 将套接字存储在 Player 对象中的目的是什么?您可以改为传递 socket.id,然后专门使用 io.to(player.socket).emit('foo'); 与该播放器通信
  • @EMX 我正在制作在线纸牌游戏。我需要在 player.js github.com/vincentwoo/setgame/blob/master/game.js#L97 中访问套接字,有一个例子,但我做不到。
  • 问题是:) 我怎样才能将“socket 推给每个玩家”
  • 为什么不显示更多代码?您似乎在尝试使用您不完全理解的代码。

标签: node.js socket.io


【解决方案1】:

如果将socket object 存储在player object 中会给您带来问题,
为什么不存储套接字的握手唯一ID?

在这里我留下一个这种方法的例子,包括一个小例子,让您的应用程序通过使用 socket.id 作为搜索存储的索引来快速访问播放器对象。

var _players = {};
io.sockets.on('connection', function(socket) {
    socket.on('login', function(data) {
        var csid = socket.id;
        var player = new Player(csid, name);
        _players[csid] = player; //Store the player in memory
    });      
    //using the memory : example (prints name of player using socket.id)
    socket.on('ask_name', function() { 
         var csid = socket.id;
         console.log(_players[csid].name);});
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-21
    • 2014-06-20
    • 1970-01-01
    • 2013-08-20
    • 1970-01-01
    • 2014-10-14
    • 2012-12-27
    • 2012-02-03
    相关资源
    最近更新 更多