Integrating Sockets in Kotlin
Tags: android, kotlin, sockets, chattingapplications
Published: 2020-11-17 15:42:45

Ever wondered how popular apps like Cricbuzz, Whatsapp, Trello, Google Docs work, or thought of building an app that gets automatic live data like a chatting app, a multiplayer game, a live quiz, etc? Then Socket.IO is the answer for you. In this article, I will illustrate how you can implement Socket.IO in your android app.

**Socket.IO is a library that enables real-time, bidirectional, and event-based communication between the client and the server.**

Socket.IO is built on top of the WebSockets API (Client-side) and NodeJs. But it is not an implementation of web sockets. It is used only for transport. Here both servers and clients can emit and listen to their calls. The server can also trigger the event on a specific route which is listened by their subscribers, which means the client has put their listener for particular events.

**Kotlin doesn’t have its official documentation for Socket.IO so we will be studying its operation from Java documentation and will translate it to Kotlin as both languages are interoperable.**

There are two methods by which you can implement Socket.IO in your native android app.
• [Socket.IO Android-Java](https://github.com/socketio/socket.io-client-java)
• [Naoyuki Kanezawa Android Socket.IO](https://socket.io/blog/native-socket-io-and-android/)

**The library provided by Naoyuki Kanezawa has also published its blog for Socket.IO using java in android. I would recommend you to use this library as it is easy to implement, provides socket (connect, disconnect, reconnect) detection, auto-reconnect feature, and is also promoted in official Socket.IO documentation.**

Now let’s move to the coding part and in the next few steps, you can set up your socket.io connection. ✌️

##Startup‍🚀

• First and foremost add the dependency to app-level build.gradle file.

{% gist https://gist.github.com/jhavidit/f5b0af30da4659fdf9704ac78a60e9ac %}


• Don’t forget to add internet permission in the manifest file. 😅

{% gist https://gist.github.com/jhavidit/ae17be81ac1c00d605ece721585c403d %}

##Socket Initialization😎

• Create a Kotlin class for socket initialization which can be used anywhere in the project. Here **IO.socket()** method returns a socket for https://yourSocketURL.com with the default options. Notice that the method **mSocket** caches the result, so you can always get the same Socket instance for an URL from any Activity or Fragment.

{% gist https://gist.github.com/jhavidit/b8c5cf6da8a0181a748fc8f0fba5bf5c %}

• Don’t forget to add your socket initialization application class name in the manifest file. 😅

{% gist https://gist.github.com/jhavidit/93059171dfec4b550d19a672c3342dbc %}

##Socket Connection to the Server😃

• Now we will create the object of the Socket Instance class which we created earlier and connect the socket using **.connect()** method. 
We will use **IO.options()** method so that socket will be reconnected by itself if ever It gets disconnected due to some network problem.

{% gist https://gist.github.com/jhavidit/e0312bb51d6664f8d5d9c4943aab87e3  %}

• To check if the socket is connected or not we can use **.connected()** method.

{% gist https://gist.github.com/jhavidit/f510407c37667f8fa1a081ca4d04ed3f  %}

##Emit and Listen Events😊

• For receiving instant real-time data we need to use **on()** method. We can get data in a JSON data block or any other data form. To show anything on the screen all the UI bind logic should be coded on the UI Thread part as the socket works on the background thread.

{% gist https://gist.github.com/jhavidit/bb589b3ed595ef36cda3389d16d2f3bd %}

• Checking when the socket is disconnected or reconnected.
{% gist https://gist.github.com/jhavidit/071006d0f0d702d2dc1b7ea58602d32b  %}
• For sending data to the server in the form of JSON data block or any other data form we have to use the **emit()** method.

{% gist https://gist.github.com/jhavidit/f9cfb9e972bfa711b82bd413bdb901a8  %}

**If you are going to receive data based on what you emit to the server then first you should start listening to the event using the on() method and then emit your data.**


• And last but not the least, don’t forget to close the socket connection using **.disconnect()** method and remove the listener using **.off()** method when you are done.😇

{% gist https://gist.github.com/jhavidit/c96d8ad6e52aef05ebd6881cd7cb575a  %}

Let me know in the comments if you have any issues and topics you would be interested in learning more about. You can also reach out to me on [Twitter](https://twitter.com/ViditJha28) and [Instagram](https://www.instagram.com/viditjha/).