Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

javascript - socket io rooms do not get any data from server

I want to create chat rooms for my react native and i write that code for my react native app:

 useEffect(() => {
    const socket = io("http://localhost:3000");
    socket.emit("new-user", "hello world");
    socket.on("room1", (data) => {
      socket.on("user-connected", (data) => {
        console.log(data);
      });
    });
    return () => {
      socket.disconnect();
    };
  }, []);

And here is the server code:

io.on("connection", (socket) => {
  console.log("made socket connection", socket.id);

  socket.on("new-user", (data) => {
    socket.join("room1");
    socket.to("room1").broadcast.emit("user-connected", data);
    console.log(data);
  });
});

The connection was established but the chat "room1" or "user-connected" do not receive any data from server. How can i listen the chat romm?

question from:https://stackoverflow.com/questions/65672026/socket-io-rooms-do-not-get-any-data-from-server

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In your server code change

socket.to("room1").broadcast.emit("user-connected", data);

to

socket.to("room1").emit("user-connected", data);

And in your client code you don't need extra socket.on("room1"). So your final client code will be like this:

useEffect(() => {
const socket = io("http://localhost:3000");
socket.emit("new-user", "hello world");
  socket.on("user-connected", (data) => {
    console.log(data);
  });
return () => {
  socket.disconnect();
};
}, []);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...