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