79558432

Date: 2025-04-06 16:12:50
Score: 1
Natty:
Report link

I would recommend you to use a popular library called Socket.io if you are into express and node. The examples I have added uses React as well.

Server

"Receive" events int the server and do the backend and database stuff.

server/index.js

const io = require('socket.io')(server, {
    // conifg options
})

io.on('connection', (socket) => {

    socket.on('setup', (userData) => {
        // Code to be executed when the socket is set.
    })

    socket.emit('connection')

    socket.on("join chat", (room) => {
        // When someone joins the chat
    })

    socket.on("new message", (newMessageReceived) => {
        // When new message is received
    })

    // Can also add any other relevant events...
})

Client

"Emit" events in the client as the user interacts.

client/components/src/ChatArea.jsx

// Setup the socket on the client side.
useEffect(() => {
    socket = io(ENDPOINT)
    socket.emit('setup', user)
    socket.on('connection', () => {
      setSocketConnected(true)
    })
  }, [])
// Emit the "new message" event.
socket.emit('new message', data)

You can refer to my chat application: https://github.com/Jay-Karia/Hello

Main files:
server: https://github.com/Jay-Karia/Hello/blob/main/server/index.js#L28-L60
client: https://github.com/Jay-Karia/Hello/blob/main/client/src/Components/ChatArea.jsx#L80


Reasons:
  • Probably link only (1):
  • Contains signature (1):
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (0.5):
Posted by: Jay