I already try to use socket io, but is just too overengineer to my propus.
I can send information with WebSocket from frontend to backend, but can't send information from backend to frontend.
I'm right now trying to use WebSocket with ws lib, but I can't send information to frontend and I don't know why.
Please, someone help?
// websocket.ts -- creating a websocket server
export async function createWebSocketServer(): Promise<typeof wss | undefined> {
try {
wss.on('connection', (ws) => {
clients.push(ws);
ws.on('message', (message) => {
console.log('Received from back: ', message.toLocaleString());
});
ws.on('close', () => {
clients = clients.filter((client) => client !== ws);
});
});
console.log('WebSocket server started on port 3005');
return wss;
} catch (error) {
console.error(error);
}
}
// /api/ml-pix/webhook -- my nextjs server. I use that line to send information to front-end, but doesnt work. Only ws lib can see that information.
const ws = new WebSocket('ws://localhost:3005');
ws.onopen = () => {
ws.send(JSON.stringify(body));
ws.close();
};
// my frontend code with a websocket hook. 'data' comes from websocket hook.
// this doesnt work. any messages was detected.
useEffect(() => {
if (open && readyState === WebSocket.OPEN) {
console.log(data);
}
return () => {
if (readyState === WebSocket.OPEN) {
}
};
}, [readyState, open]);
I already try to use socket io, but is just too overengineer to my propus.
I'm right now trying to use WebSocket with ws lib, but I can't send information to frontend and I don't know why.