How can I get the socket ID from an event in Socket.io?

霸气de小男生 提交于 2019-12-11 14:49:21

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/26725488/how-can-i-get-the-socket-id-from-an-event-in-socket-io

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!