skip to Main Content

I am using React and socket.io to transmit a message to all the connected devices. Please find the mistake. Any help is appreciated.

App.js

import { useRef } from "react";
import { io } from "socket.io-client";
const socket = io("http://localhost:4000");

const App = () => {
  const messege = useRef(null);
  //socket functions
  socket.on("connect", () => {
    console.log("connected: " + socket.id);
  });
  socket.on("recieve", (msg) => {
    console.log(msg);
  });

  const send = () => {
    const message = messege.current.value;
    socket.emit("message", message);
  };

  return (
    <div>
      <input type="text" placeholder="Message" ref={messege} />
      <button onClick={send}>Send</button>
    </div>
  );
};

export default App;

Server.js

const { Server } = require("socket.io");

const io = new Server(4000, {
  cors: {
    origin: ["http://localhost:5173"],
  },
});

io.on("connection", (socket) => {
  console.log(`connected with id: ${socket.id}`);
  socket.on("message", (msg) => {
    console.log(msg);
    socket.emit("recieve", msg);
  });
});

It only prints the message only to the emitter client(not other connected client).

2

Answers


  1. Chosen as BEST ANSWER

    I found the mistake for which I could not receive messages in all active clients.

    The mistake was in server.js

    const { Server } = require("socket.io");
    
    const io = new Server(4000, {
      cors: {
        origin: ["http://localhost:5173"],
      },
    });
    
    io.on("connection", (socket) => {
      console.log(`connected with id: ${socket.id}`);
      socket.on("message", (msg) => {
        console.log(msg);
        socket.emit("receive", msg);
        // before it was socket.emit("receive", msg);
      });
    });
    

    the message should be emitted from io instead of socket as we want to send all the connected user.


  2. Try using rooms

    io.on("connection", socket => {
      socket.join("receive")
      socket.join(user.id) // room for this user only (multiple connected device)
    
      socket.on('message', msg => {
          socket.to("receive").emit(msg)
      })
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search