How to Send a Message to a Particular Client with Socket.Io

How to send a message to a particular client with socket.io

When a user connects, it should send a message to the server with a username which has to be unique, like an email.

A pair of username and socket should be stored in an object like this:

var users = {
'userA@example.com': [socket object],
'userB@example.com': [socket object],
'userC@example.com': [socket object]
}

On the client, emit an object to the server with the following data:

{
to:[the other receiver's username as a string],
from:[the person who sent the message as string],
message:[the message to be sent as string]
}

On the server, listen for messages. When a message is received, emit the data to the receiver.

users[data.to].emit('receivedMessage', data)

On the client, listen for emits from the server called 'receivedMessage', and by reading the data you can handle who it came from and the message that was sent.

Send message to specific client with socket.io and node.js

Well you have to grab the client for that (surprise), you can either go the simple way:

var io = io.listen(server);
io.clients[sessionID].send()

Which may break, I doubt it, but it's always a possibility that io.clients might get changed, so use the above with caution

Or you keep track of the clients yourself, therefore you add them to your own clients object in the connection listener and remove them in the disconnect listener.

I would use the latter one, since depending on your application you might want to have more state on the clients anyway, so something like clients[id] = {conn: clientConnect, data: {...}} might do the job.

socket.io and node.js to send message to particular client

Try this:

socket.on('pmessage', function (data) {
// we tell the client to execute 'updatechat' with 2 parameters
io.sockets.emit("pvt",socket.username,data+socket.username);
io.sockets.socket(socket.id).emit("pvt",socket.username,data+socket.username);
});

socket.id is saved by socket.io and it contains unique id of your client.
You can check that using this:

console.log(socket.id);

I want to send a message to a particular client with socket.io in swift (IOS)?

You should configure it on server and on client.

Here my question from long ago but I'll explain it here too.

Each of your user connected you should gave it ID. Store it on database or whatever map could be use to. Remember ID must be unique like emails, userid or whatever unique.

Server.js

const sessionsMap = {}; // I save user ID here

io.on('connection', (socket) => {
socket.emit('askForUserId');

socket.on('userIdReceived', (userId) => {
sessionsMap[userId] = socket.id; // save the users on database or Object up to you
});

socket.on('send', (message) => {
const receiverId = sessionsMap[message.receiverId];
const messageData = message.data;
socket.broadcast.to(receiverId).emit('mymessage', messageData);
});
});

Client

Sorry I don't know swift but its same (I hope you get the point), servers handle the message send to who and came to who.

const userId = 'julia@mail.me'; // this should be unique

io.on('askForUserId', () => {
io.emit(userId); // your connected user ID save it.
});

io.on('mymessage', (message) => {
console.log('Yoho had message from', message.senderId)
console.log(message.text)
});

// send message to other people
io.emit('send', { text: 'Hellow', receiverId: 'john@doe.net', senderId: 'julia@mail.me' })

How do i make socket.io send emit message to only one client?

I guess one of the comments directs you to a few potential answers. But just in case a struggling coder has the same issue, here is what i did that resolved it.

server.js

io.on('connection', function(socket) {
io.to(socket.id).emit('private', `your secret code is ${code}`);
});

client.js

socket.on('private', function(msg) {
alert(msg);
});

https://socket.io/docs/v4/emit-cheatsheet/ has a bunch of useful information in a small amount of text. Also heres the link to the other question in case you want to know more then one solution:

Send message to specific client with socket.io and node.js

Send specific message to specific socket.id with socket.io

You need to maintain a map of _socket_id/user_id_

Server

const sessionsMap = {};

io.on('connection', (socket) => {
socket.emit('askForUserId');

socket.on('userIdReceived', (userId) => {
sessionsMap[userId] = socket.id;
});

socket.on('send', (message) => {
const receiverId = sessionsMap[message.receiverId];
const messageData = message.data;
socket.broadcast.to(receiverId).emit('my message', messageData);
});
});

Client

const userId = 'FOO';

io.on('askForUserId', () => {
io.emit(userId);
});

io.on('send', (message) => {
console.log('You received a message');
console.log(message.data);
});

Note

Make sure to check out the Socket.IO cheatsheet it covers a lot of commands and use cases.



Related Topics



Leave a reply



Submit