Next.js Discord

Discord Forum

broadcast send message to sender too!! (socket.io)

Unanswered
Chub mackerel posted this in #help-forum
Open in Discord
Avatar
Chub mackerelOP
I woking on a chat app, I add this on node.js server
import { Server } from "socket.io";

const io = new Server(3000, { cors: "*" });

io.on("connection", (socket) => {
  console.log("A user connected:", socket.id);

  socket.on("send-message", ({ message }) => {
      socket.broadcast.emit("recive-message", {message});
  });
});

and my expect is when I send message from tab A to tab B, just in tab B, I see alert. But I see in both tab
frontend code
    useEffect(() => {
        socket.on("connect", () => {
            setSocketId(socket.id);
        });

        socket.on("recive-message", ({ message, senderId }) => {
            alert(message);
            // setMessages((prev) => [...prev, { id: v4(), text: message, author: "bot" }]);
        });

        return () => {
            socket.disconnect();
            socket.on("disconnected", () => {
                console.log("disconnected from socket");
            });
        };
    }, []);

0 Replies