如何从Socket.io中的事件获取套接字ID? [英] How can I get the socket ID from an event in Socket.io?
本文介绍了如何从Socket.io中的事件获取套接字ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道哪个客户端在服务器上到达时发送了事件.例如:
I want to know which client sent an event when it arrives on the server. For example:
var socket = require(socket.io')(port);
socket.on("ask question", function(data){
var socketid = // ?
//respond to sender
socket.sockets.connected[socketid].emit("Here's the answer");
});
如何获取事件发送者的套接字ID?
How can I get the socket ID of the event sender?
推荐答案
您的服务器端逻辑有些偏离.客户端连接,这是显示客户端套接字的位置,也是您侦听特定客户端事件的位置.通常,它看起来像这样:
Your server-side logic is a bit off. The client connects and that's where the client socket is revealed and that's where you listen to events from a particular client. Usually, it would look like this:
var io = require("socket.io")(port);
io.on('connection', function (socket) {
socket.on('ask question', function (data) {
// the client socket that sent this message is in the
// socket variable here from the parent scope
socket.emit("Here's the answer");
});
});
这在socket.io docs 此处中显示.
This is shown in the socket.io docs here.
这篇关于如何从Socket.io中的事件获取套接字ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文