Real-Time Chat Applications

Salonix__
3 min readFeb 1, 2021

Chat Applications are trending worldwide nowadays, people use it to communicate with friends, family, etc, and hence makes these messaging application an essential medium for communication.

Have you ever thought how these real-time messaging things work? Let’s dive deep into this interesting topic.

Broadly speaking, a chat application has three main components:

  • Messaging Application
  • Server
  • A persistent connection

This is the only component that you see on any chat application, rest of them works in backend.

Real-time messaging on the web typically involves a system where data is streamed from sender to receiver or vice-versa. XMPP, WebSockets, and HTTP Long Polling is a good example of a real-time messaging protocol that offers high customizability and extensionality on top of which a real-time application can be built.

Now, let’s talk about the connection from which data streams from server to client and client to server. The app connects to a corresponding chat central server, which makes users send messages to each other. Now two types of messages can be transferred:

  • One-to-one
  • Group Chats

Now, the first step is user-identification, which is usually done by sending OTP to a number and hence verifying the user. Once verified, the server affixes your identity to the map of connections. Every user’s identity information is mapped with a particular connection. If a user PersonA wants to send some message to some other user PersonB. The message first emerges from PersonA’s messenger, travels through the connection between PersonA and server, now the server identifies the connection between itself and receiver i.e., PersonB, and then sends the message to the receiver.

For group conversation, we usually create a channel, in which different users subscribe and then can send messages to that channel, and everyone on that group would be able to see messages.

Group Chat Workflow:(I have used Rails for server)

  • Create a server-side WebSocket channel called room_channel that will have methods for when a client subscribes and unsubscribes, and a method for sending data to the client.
  • Create a client-side representation of the channel that will be called RoomChannel (note the naming convention). It will subscribe to the server-side channel and will have methods which will be fired on connecting/disconnecting from the server and methods for handling, sending and receiving data.
  • Make a Rails Job that will queue the new message to be created in the database and broadcast it back through the WebSocket channel after it is created.

Thanks for reading, any suggestion for improvement will be appreciated :)

--

--