簡體   English   中英

如何從Socket.io中的事件獲取套接字ID?

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

我想知道事件到達服務器時哪個客戶端發送了事件。 例如:

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?

您的服務器端邏輯有些偏離。 客戶端連接,這是顯示客戶端套接字的位置,也是您偵聽特定客戶端事件的位置。 通常,它看起來像這樣:

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文檔這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM