gpt4 book ai didi

javascript - socket.io 在回调中获取套接字

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

我正在为 node.js 使用 socket.io。如果您添加这样的事件处理程序:

io = require('socket.io')(http);
io.on('connect',function(socket){
socket.on('some event',function(arg1,arg2){
/// using socket to emit events for example
}
}

然后我可以在“某些事件”的回调中访问套接字但是,如果我这样使用它呢

io = require('socket.io')(http);
io.on('connect',function){
socket.on('some event',myfunction);
}

function myFunction(arg1,arg2)
{
//I want to use calling socket here.
}

在后一种情况下如何访问套接字?我需要套接字来获取 socket.id,这样我才能知道是谁调用了这个事件。谢谢

最佳答案

好吧,如果我明白你想做什么,你可以简单地:

io = require('socket.io')(http);
io.on('connect',function){
socket.on('some event',myfunction);
}

function myFunction(arg1,arg2)
{
var socketId = this.id; //here you go, you can refer the socket with "this"
}

这是我通常用来保持代码整洁的做法:

var on_potato = function(potatoData){

var socket = this;
var id = socket.id;

//use potatoData and socket here
};

var on_tomato = function(tomatoData){

var socket = this;
var id = socket.id;

//use tomatoData and socket here
};

var handleClientConnection = function (client) {

client.on('potato', on_potato);
client.on('tomato', on_tomato);
};

io.on('connection', handleClientConnection)

关于javascript - socket.io 在回调中获取套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30903162/

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