Socket.io send disconnect event with parameter

前端 未结 2 1911
既然无缘
既然无缘 2021-01-14 20:56

I want to send disconnect event manually with custom parameter to socket.io server. I use this function but won\'t work:

//client

var userId = 23;
so         


        
2条回答
  •  南方客
    南方客 (楼主)
    2021-01-14 21:28

    We can manage a global array at server side.

    var sockets = [];
    io.on('connection', function (socket) {
        const id = socket.id ;
    
        socket.on('user-join', function(data) {
             sockets[id] = res.id;
        });
    
        socket.on('disconnect', function(data) { 
            io.emit('user-unjoin', {user_id: sockets[id],status:'offline'}); 
        });
    });
    

    On clients side,

    socket.on('user-unjoin', function (data) {
        // update status of data.user_id according to your need.
    });
    

    This answer is inspired from Jackthomson's answer.

提交回复
热议问题