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
I found the mistake for which I could not receive messages in all active clients.
The mistake was in
server.js
the message should be emitted from
io
instead ofsocket
as we want to send all the connected user.Try using
rooms