How develop realtime chat application in 2019? — part II

In this part of the series, I will mention how manage realtime communication between a client to another clients. This is the most important thing in a realtime based application.

Events Logic

Socket.io is utterly event-based library.

Socket.io Communication Logic

Communication Basics

  • A client cannot emit anything to another client.
  • A client can only emit event to a socket.io server.
  • A client can listen events which emitted by a socket.io server.

Data Transfer Basics

  • You can pass data during emitting, on client and server side.
  • You can retrieve acknowledgement to be ensure to emitting is successful.

Events

In my projects, I had nine events on server-side. I will mention two of these.

  • User Connection event
  • Message event

Connection Event

When a user enters the app, we need update user’s online status.

Then, client must inform server about this event. This event’s identifier is a constant string and defined client and server side: “CONNECTION_EVENT

Client also transfer own’s UserModel during emitting to server.

Server handles UserModel, and invoke setConnectionStatus() method to send request API to set user online and also set user’s unique socket id.

server’s user connection handling

Message Event

The another important event was messaging event, I think we can analyze this event’s handling client and server-side.

When a user sends a message to another user, client emits a MessageModel to server. You can see model below:

MessageModel.java

Server handles this emitting and pass event to only receiver user. Also, socket server decides a message’s date.

server’s messaging handling

On client side, receiver handles event like below. addMessageToList() method, adds message to chat screen.

ChatFragment.java

Thank you for using your precious time to reading this article. If you liked it clap your 👏 to say “thanks!” and help others find this article.