javascriptreactjsnode.jssocket.ioconnection

Socket.io not receiving data properly in React and Node JS


`I am trying to build a connection between a web application and a frontend using socket.io. I want it so that anytime I click on a button, I receive the JSON data that is being sent from the server side (web app) to the client (frontend). The server side is built with express/node and the client is built with react.

I click on the first button, and the JSON message "hello" appears. When I click "done with JSON", I do not get another JSON message and instead get "Done with JSON" Anyone know how to solve this?

//////server side
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');



const app = express();
const server = app.listen(8080);
const io = require('socket.io')(server, {
    cors: {
      origin: '*',
    }
});
PORT = 8080;


app.get('/', (req, res) => {
    res.send('Socket.IO Server Running');
});

io.on('connection', (socket)=>{
    console.log("Connected");

      //this messsage is sent and received by the client
    const firstJson = {message:"hello"};
    socket.emit("receiveJson", firstJson);

    socket.on('jsonProcessed', () => {
        console.log('Client has processed the first JSON.');
        setTimeout(() => {
                  //this message is not received by the client
            const secondJson = { message: 'This is your second JSON!' };
            socket.emit('receiveJson', secondJson);
        }, 1000); // 1-second delay
    });
    
    socket.on('disconnect', ()=>{
        console.log('User disconnected');
    });
});



//Client side
import React, {useRef, useState, useEffect} from 'react';
import { useNavigate } from 'react-router-dom';
import io from 'socket.io-client';
const Male = ({title})=>{
    const navigate = useNavigate();
    const socket = io('http://localhost:8080');

   
        const [jsonData, setJsonData] = useState(null);

        useEffect(()=>{
            socket.on('connect',()=>{
                console.log('Connection to server established');
            })
            socket.on('receiveJson',(data)=>{
                console.log('Received JSON from server: ', data);
                setJsonData(data);

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

        const handleJsonProcessing = () =>{
            console.log('Emitting jsonProcessed event');
            
            socket.emit('jsonProcessed');
            setJsonData(null);
        };
return(

</div>
                        {jsonData ? (
                <div>
                    <pre>{JSON.stringify(jsonData, null, 2)}</pre>
                    <button onClick={handleJsonProcessing}>Done with JSON</button>
                </div>
            ) : (
                <p>No JSON data received.!!</p>
            )}
);
};

It might also help if I show my console statements, which come up here:[log statements](https://i.sstatic.net/X9eFBDcg.png)


Solution

  • Here's an updated version that should work:

    // server
    const express = require("express");
    const http = require("http");
    const { Server } = require("socket.io");
    
    const app = express();
    const server = app.listen(8080, () => {
      console.log("Server is running on port 8080");
    });
    
    const io = require("socket.io")(server, {
      cors: {
        origin: "*",
      },
    });
    
    app.get("/", (req, res) => {
      res.send("Socket.IO Server Running");
    });
    
    io.on("connection", (socket) => {
      console.log("Connected");
    
      // This message is sent and received by the client
      const firstJson = { message: "hello" };
      socket.emit("receiveJson", firstJson);
    
      socket.on("jsonProcessed", () => {
        console.log("Client has processed the first JSON.");
        setTimeout(() => {
          // This message is not received by the client
          const secondJson = { message: "This is your second JSON!" };
          socket.emit("receiveJson", secondJson);
        }, 1000); // 1-second delay
      });
    
      socket.on("disconnect", () => {
        console.log("User disconnected");
      });
    });
    
    
    // client
    import io from "socket.io-client";
    import React, { useRef, useState, useEffect } from "react";
    
    const Male = ({ title }) => {
      const socket = useRef(null);
      const [jsonData, setJsonData] = useState(null);
    
      useEffect(() => {
        socket.current = io("http://localhost:8080");
    
        socket.current.on("connect", () => {
          console.log("Connection established");
        });
        
        socket.current.on("receiveJson", (data) => {
          console.log("Received: ", data);
          setJsonData(data);
        });
        
        return () => {
          console.log("Disconnected");
          socket.current.disconnect();
        };
      }, []);
    
      const handleProcessing = () => {
        console.log("Emitting event");
        socket.current.emit("jsonProcessed");
        setJsonData(null);
      };
    
      return (
        <div>
          {jsonData ? (
            <div>
              <pre>{JSON.stringify(jsonData, null, 2)}</pre>
              <button onClick={handleProcessing}>Done</button>
            </div>
          ) : (
            <p>No data received.</p>
          )}
        </div>
      );
    };
    
    export default Male;