How can I get the socket ID from an event in Socke

2019-09-20 02:16发布

问题:

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.