Sometimes,. we want to send a message to a particular client with Node.js socket.io.
In this article, we’ll look at how to send a message to a particular client with Node.js socket.io.
How to send a message to a particular client with Node.js socket.io?
To send a message to a particular client with Node.js socket.io, we can call sockets.in
before calling emit
.
For instance, we write
const socket = io.connect('http://localhost');
socket.emit('join', {
email: '[email protected]'
});
on client side to connect to the socket.io server.
Then on server side, we write
const io = require('socket.io').listen(80);
io.sockets.on('connection', (socket) => {
socket.on('join', (data) => {
socket.join(data.email);
io.sockets.in('[email protected]').emit('msg', {
msg: 'hello'
})
});
});
to create a socket.io server.
And we listen for 'join'
events that are emitted by clients.
We get the data from the object in the 2nd argument of emit
from data
.
Then we call io.sockets.in
with '[email protected]'
and then call emit
to send data to the client with email
'[email protected]'
Conclusion
To send a message to a particular client with Node.js socket.io, we can call sockets.in
before calling emit
.