【问题标题】:Which is the prefered way to add function to sockets in socket.io?在 socket.io 中向套接字添加功能的首选方式是什么?
【发布时间】:2015-07-18 14:05:56
【问题描述】:

是否有连接到 socket.io 的所有套接字的“原型”?

我想定义一些可用于每个连接的套接字的函数。

目前我有:

io.sockets.on('connection', function(socket) {
  //Define properties and functions for socket
  socket.hello = function(){
    console.log("hello from "+socket.id);
  }

  socket.hello();
});

但我正在为每个套接字定义一个“新”hello 函数。有插座原型吗?所以我可以有类似的东西:

Socket.prototype.hello = function(){
  console.log("hello from "+socket.id);
}

io.sockets.on('connection', function(socket) {
  socket.hello();
});

【问题讨论】:

    标签: javascript node.js sockets socket.io


    【解决方案1】:

    有,但似乎无法通过主要的require('socket.io') 获得。

    目前,您必须直接require() socket.js 来引用它:

    var Socket = require('socket.io/lib/socket');
    
    Socket.prototype.hello = function () {
        console.log("hello from " + this.id);
    };
    

    注意:从prototype,您必须将实例引用为thissocket 变量将不可用。

    另外,就像反对修改本机类型的建议一样,例如 Objectprototype - 只有一个 Socket.prototype,因此在尝试定义相同方法时可能会遇到多个模块的冲突。

    【讨论】:

    • 原型中的“socket.id”是一个错字...但感谢您的澄清:)
    • 抱歉,您需要在var io = require('socket.io')(server); 之前添加这个吗?无法让它工作......
    【解决方案2】:

    使用 typescript 向 Socket 添加函数

    创建一个 Extension.ts 文件

    const Socket = require('socket.io/lib/socket')
    
    declare module 'socket.io' {
        interface Socket {
            getGameKey(this: typeof Socket): string
            getToken(this: typeof Socket): string
        }
    }
    
    function getGameKey(this: typeof Socket): string {
        return this.handshake.query.gameKey
    }
    
    function getToken(this: typeof Socket): string {
        return this.handshake.query.token
    }
    
    Socket.prototype.getGameKey = getGameKey;
    Socket.prototype.getToken = getToken;
    
     
    

    然后在需要访问新添加的方法(即getToken和getGameKey)的地方导入扩展文件

    import './Extension'
    
    io.on("connection", socket => {
        console.log("Game key "+socket.getGameKey())
        console.log("Token "+socket.getToken())
    })
    

    【讨论】:

      猜你喜欢
      • 2016-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多