I am trying to log the socket id when a user logs out of a chat room. Currently the logger is saying 'transport close has left the chatroom' instead of logging the socket id.
I have been able to get it to log 'transport close' or 'undefined' but can't seem to get it to save the socket.id before the connection closes. What am I doing wrong?
io.on('connection', function(socket){
var user_id = socket.id;
io.emit('broadcast', `--${user_id} has joined the chat room`);
console.log(`[${user_id}] has joined the chat room`);
socket.on('chat message', function(msg){
io.emit('chat message', `[${user_id}] ${msg}`);
console.log(`[${user_id}] ${msg}`);
});
socket.on('disconnect', function(user_id){
io.emit('broadcast', `${user_id} has left the chat room`);
console.log(`${user_id} has left the chat room`);
})
});
Use socket.id
instead of user_id
. Your callback function(user_id)
is incorrect.
socket.on('disconnect', function(){
io.emit('broadcast', socket.id + ' has left the chat room');
console.log(socket.id + ' has left the chat room');
})