Categories
JavaScript Answers

How to send a message to a particular client with socket.io and JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *