javascript - How can i map client id with their respective sockets in node.js? -
good day all, i'm playing socket.io in nodejs,i'm working on chat application,on front end user has list of connected users if user clicks particular user list , sends message front-end so.
sendmessage: function (event) { if (event.keycode == 13) { let target = event.target; var msg = target.value; //create object of chatschema var packet={"chatid":"","userid":"","username":this.state.localusername,"message":msg, "socketid":socket.id,"to":this.props.remoteusername}; console.log('packet: '+packet.message); // socket.emit('chat mssg', msg, socket.id,packet); socket.emit('chat mssg', packet); // alert('pushing msg '); var newlocalmsg = this.state.localstatemessages; var allmsgs = this.state.allmessages; var message = { "message": msg, "mesgtype": "local" }; allmsgs.push(message); newlocalmsg.push(msg); this.setstate({ localstatemessages: newlocalmsg, messagetype: 'local', allmessages: allmsgs }); target.value = ''; } }
the packet i'm sending server includes information user user message being sent along socketid of user sending message. on server side i'm handling event so
socket.on('setup localuser',function(person){ console.log(person.firstname+' connected id:'+socket.id); console.log(person); //push socketid client[] along username; clients.push({"socketid":socket.id,"username":person.firstname}); }) socket.on('chat mssg', function (packet) { console.log(packet.username+' wants send message '+packet.to); console.log(packet.username +':'+ packet.message ); //iterate through clients , find connected socket associated intended recipent , emit msg var receiver=clients.find(function(client){ return client.username===packet.to; }) io.sockets.connected[receiver.socket.id].emit('chat mssg',packet.username+ ':'+packet.message); console.log(receiver.username); console.log('socket id :' + socket.id); })
what i'm doing pushing each socketid along username array clients , on reception of event 'chat mssg' i'm iterating through clients array , trying find socket.id of user whom message sent , emit event on socketid doesn't work, doesn't print receiver.username console,the receiver variable goes undefined in case. tried clients.map() didn't me required intended recipient either. how can it? thank helping me :d
Comments
Post a Comment