node.js - Make a new prop in socket io object and get undefined using react.js as client -
i trying store data socket prop can reference later. however, on others socket.on comes out undefined
here code:
var userlist = ['dang huy','alice','bui sam', 'hai hai']; var onlineuser = []; io.on('connection', socket => { socket.on('useronline', (data) => { //user alice go in if(userlist.includes(data)){ onlineuser.push(data); io.sockets.emit('onlineuser', onlineuser); } socket.user_name = data; // store data user_name console.log(socket.user_name + ' online'); //logout alice online }) socket.on('usersendmessage', (data) => { console.log(socket.user_name) // socket.user_name undefined here!! console.log(data) // still log out message client side io.sockets.emit('serversendmessage', 'hello') }) socket.on('disconnect', function(){ onlineuser.splice(onlineuser.indexof(socket.user_name), 1) io.sockets.emit('onlineuser', onlineuser) }) })
what mean next event (could provides example?)oh notice wrong , won't never go event , purely normal, socket scope variable {}
& ask out of them, move listeners up:
var userlist = ['dang huy','alice','bui sam', 'hai hai']; var onlineuser = []; io.on('connection', socket => { socket.on('useronline', (data) => { //user alice go in if(userlist.includes(data)){ onlineuser.push(data); io.sockets.emit('onlineuser', onlineuser); } socket.user_name = data; // store data user_name console.log(socket.user_name + ' online'); //logout alice online }) socket.on('usersendmessage', (data) => { console.log(socket.user_name) // socket.user_name undefined here!! console.log(data) // still log out message client side io.sockets.emit('serversendmessage', 'hello') }) socket.on('disconnect', function(){ onlineuser.splice(onlineuser.indexof(socket.user_name), 1) io.sockets.emit('onlineuser', onlineuser) }) })
Comments
Post a Comment