Sometimes, we want to send a message to a particular client with socket.io and JavaScript.
In this article, we’ll look at how to send a message to a particular client with socket.io and JavaScript.
How to send a message to a particular client with socket.io and JavaScript?
To send a message to a particular client with socket.io and JavaScript, we call the socket.emit
and socket.on
method.
For instance, on client side, we write
const socket = io.connect("http://localhost");
socket.emit("join", { email: "user1@example.com" });
to call socket.emit
to emit the join
event with some event data.
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);
});
});
to call io.sockets.on
with 'connection'
to listen to the connection event.
In the callback, we call socket.on
with 'join'
to listen to the join
event.
In the join
callback, we get the email
value we sent from data.email
.
Conclusion
To send a message to a particular client with socket.io and JavaScript, we call the socket.emit
and socket.on
method.