» Node.js: Make Web Chat App with Socket.IO » 2. Development » 2.3 Chat Messages

Chat Messages

To the server side, one-on-one chat is basically to forward messages from one socket to another.

Update app.js:

@@ -25,6 +25,11 @@ io.on("connection", (socket) => {
     // Broadcast to all connected clients
     io.emit("contacts", Array.from(users.entries()));
   });
+
+  socket.on("chat", (data) => {
+    const { to } = data;
+    io.to(to).emit("chat", data);
+  });
 });
 
 // Start the server

data has below fields:

  • to: destination socket ID of the incoming message.
  • from: socket ID of the sender.
  • msg: message content.

io.to() is a method provided by Socket.IO that allows you to target specific sockets or rooms when emitting events.

PrevNext