2

I´ve been searching for the anwser but most of them i cant quite connect with my code so im hoping to get some help.

I want to send a message for a specific user, like a chat beetween 2 people.

For example, if i choose John how can i only send a mensage to him? im having much trouble in this

enter image description here

app.js

io.on('connection', function (socket) { socket.on('chat', function (data) { console.log(data); //Specific user //socket.broadcast.to(socketid).emit('message', 'Hello'); }); }); 

I have a mongodb database so how can i specify the socketid having the user id of the select user?

2 Answers 2

1

The below code can be used to send message to a specific client. Point to be noted , every client connected has a unique socket id. Store that id in an array. You can call any user with that id.

var id=[]; io.on('connection', function (socket) { socket.on('chat', function (data) { console.log(data); id.push(${socket.id}); }); }); //to send to specific user io.to(socket#id).emit('hey!') 
Sign up to request clarification or add additional context in comments.

Comments

0

You must create an userbased array. Here, you can get a special socket:

var users = []; io.on('connection', function (socket) { users.put(socket); socket.on('chat', function (data) { console.log(data); users[0].emit('chat', data); }); }); 

You can use a array based or an object based (here you can store it with the username, but you must implement a procedure to set the username after connection is available) variable.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.