[英]How can I get the socket ID from an event in Socket.io?
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");
});
How can I get the socket ID of the event sender? 如何获取事件发送者的套接字ID?
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");
});
});
This is shown in the socket.io docs here . 这显示在socket.io文档这里 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.