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.
Socket.io is utterly event-based library.
- 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.
In my projects, I had nine events on server-side. I will mention two of these.
- User Connection event
- Message 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.
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:
Server handles this emitting and pass event to only receiver user. Also, socket server decides a message’s date.
On client side, receiver handles event like below. addMessageToList() method, adds message to chat screen.
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.