Categories
JavaScript Answers

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

Spread the love

To send a message to a particular client with socket.io and JavaScript, we use the join method.

For instance, we write

const socket = io.connect("http://localhost");
socket.emit("join", { email: "user1@example.com" });

to emit the join event on client side.

Then we write

const io = require("socket.io").listen(80);

io.sockets.on("connection", (socket) => {
  socket.on("join", (data) => {
    socket.join(data.email);
  });
});

to listen to the join event with on and call join in the handler to add the client to the chat room.

Next, we write

io.sockets.in("user1@example.com").emit("new_msg", { msg: "hello" });

to call in to get the chat room and call emit to emit the new_msg event with the content on server side.

Then we write

socket.on("new_msg", (data) => {
  console.log(data.msg);
});

to listen to the new_msg on client with on.

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 *