gpt4 book ai didi

javascript - 在 socket.io 中向套接字添加功能的首选方法是什么?

转载 作者:搜寻专家 更新时间:2023-11-01 00:42:24 25 4
gpt4 key购买 nike

是否存在连接到 socket.io 的所有套接字的“原型(prototype)”?

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

目前我有:

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

socket.hello();
});

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

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

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

最佳答案

虽然它似乎无法通过主 require('socket.io') 获得。

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

var Socket = require('socket.io/lib/socket');

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

Note: From the prototype, you'll have to reference the instance as this. A socket variable won't already be available.

Also, like the recommendations against modifying native types, like Object's prototype -- there's only one Socket.prototype, so it's possible to run into collisions of multiple modules trying to define the same method.

关于javascript - 在 socket.io 中向套接字添加功能的首选方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30110578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com