Chat Application
MERN chat application I made with the team at Hatchways. This project is a Realtime Chat Application using Socket.io.
Summary
TL;DR — MERN chat application I made with the team at Hatchways. This project is a Realtime Chat Application using Socket.io.
Websockets vs Rest
Traditionally HTTP is a request, response model, and it closes the connection after each data packet it sent. Websockets a more akin to phone conversation. You open a session transfer some data and then close the session.
Keeping the connection between the server and the client alive. This allows users to communicate in real-time.
Why is that useful?
Without web sockets, the chat client has to poll the server to find out if there are any new messages. With web sockets, when a new message arrives, the server can blast the message out to your browser.
An example is shown below.
io.on('connection', (socket) => {
socket.emit('request', /_ … _/) // emit event to the socket
io.emit('broadcast', /_ … _/) // emit event to connected sockets
socket.on('reply', () => {
;/_ … _/
}) // listen to the event
})
This application is a great example of the benefits of a persistent connection; it’s bidirectional, i.e. either party can send a message to the other party at any time. This makes it useful for things like push notifications and real-time updates.
Socket.io also brings to the table nice features like rooms and, most importantly, message callbacks. Here you can see we can use socket.io to help us broadcast to users that someone has joined the room:
io.on('connection', (socket) => {
socket.on('join', ({ name, room }, callback) => {
const { error, user } = addUser({ id: socket.id, name, room })
if (error) return callback(error)
socket.join(user.room)
socket.broadcast
.to(user.room)
.emit('message', { user: 'admin', text: `${user.name} has joined!` })
io.to(user.room).emit('roomData', {
room: user.room,
users: getUsersInRoom(user.room),
})
callback()
})
})
Demo
Thanks a lot for reading! Source code is available on my github.