Rihab sabri
Rihab sabri

Reputation: 381

Socket.emit is not working under socket.on in the server side

I am trying to use socket IO in my project, I established a socket connection and I can see when users join and leave and enter rooms, Now i want to generate an admin message when a user joins the room to welcome them but it is not working at all nor showing me any warnings or errors.

Being new to this I don't know what is the problem, When I emit a socket it works fine but when I nest it, things seem to stop so I wonder why?

Here is the server side code :

const express = require("express");
const app = express();
const http = require("http");
const cors = require("cors");
const { Server } = require("socket.io");

app.use(cors());

const server = http.createServer(app);

const io = new Server(server, {
  cors: { origin: "http://localhost:3000", methods: ["GET", "POST"] },
});

io.on("connection", (socket) => {
  console.log(`user ${socket.id} has joined`);
  socket.on("join", (data) => {
    console.log(data.room);
    socket.join(data.room);
    console.log(`User with ID: ${socket.id} joined room: ${data.room}`);
    io.sockets.emit("message", {
      user: "admin",
      text: `${data.name}, welcome to room ${data.room}.`,
    });
    // socket.broadcast
    //   .to(data.room)
    //   .emit("message", { user: "admin", text: `${data.name} has joined!` });
  });
  socket.on("disconnect", () => {
    console.log(`user ${socket.id} has left`);
  });
});

server.listen(3001, () => {
  console.log("server is Up");
});

and here is the frontend code:

import io from "socket.io-client";
import { useState } from "react";
import Chat from "./routes/chat/Chat";
const socket = io.connect("http://localhost:3001");

function App() {
  const [name, setName] = useState("");
  const [room, setRoom] = useState("");
  const joinRoom = () => {
    if (name !== "" || room !== "") {
      socket.emit("join", { name, room });
    }
  };
  return (
    <div className="App">
      <input
        type="text"
        placeholder="name"
        onChange={(event) => {
          setName(event.target.value);
        }}
      />
      <input
        type="text"
        placeholder="room"
        onChange={(event) => {
          setRoom(event.target.value);
        }}
      />
      <button onClick={joinRoom}>JOIN</button>

      <Chat socket={socket} name={name} room={room} />
    </div>
  );
}

export default App;

I added all the code in case the error is coming from something unrelated to sockets.

Upvotes: 0

Views: 770

Answers (1)

Rihab sabri
Rihab sabri

Reputation: 381

I thought because the event emitter for admin message was nested inside socket.on('join'...) I didn't need to listen for it on the client side: But I have added this on the frontend, now it is working but I would still like to see if this is a good solution.

  const [name, setName] = useState("");
  const [room, setRoom] = useState("");
  const joinRoom = () => {
    if (name !== "" || room !== "") {
      socket.emit("join", { name, room });
      socket.on("message", (message) => {
        console.log(message);
      });
    }
  };

Upvotes: 0

Related Questions