`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