JavaScript Answers

How to send a message to a particular client with and JavaScript?

Spread the love

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

For instance, we write

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

to emit the join event on client side.

Then we write

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

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

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"").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) => {

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 *