Best practices of Socket.io with Android

Nikhil Chaudhari
4 min readMar 14, 2018

--

Socket.IO enables real-time bidirectional event-based communication. It works on every platform, browser or device, focusing equally on reliability and speed. Socket.IO is built on top of the WebSockets API (Client side) and NodeJs.

Socket.IO is not a WebSocket library with fallback options to other realtime protocols. It is a custom realtime transport protocol implementation on top of other realtime protocols. Its protocol negotiation parts cause a client supporting standard WebSocket to not be able to contact a Socket.IO server.
And a Socket.IO implementing client cannot talk to a non-Socket.IO based WebSocket or Long Polling Comet server. Therefore, Socket.IO requires using the Socket.IO libraries on both client and server side.

The official site says,

Socket.IO enables real-time bidirectional event-based communication.

The Socket.IO enables the client and server to communicate in real time. The Socket.IO NodeJs server defines the events that to be triggered on a specific route.Those events are listened by server which are emitted by clients.Also, a server can emit an event to which a client can listen.

The Socket.IO can easily be implemented over web apps using NodeJs server as a back-end. But in case of Android ?

Then we have a best library created by Naoyuki Kanezawa [@nkwaza].
and one by official Socket.IO Github for android as client of Socket.IO server.

It depends on you what do you want to choose as your personal preference.
0]Socket.Io Android-Java client

1]Nkwaza Android Socket.IO client library

you can use either of them. I would recommend you the Second one because it’s very handy and kinda easy to use.
You can go through the official blog on Socket.IO site by NKwaza.

To implement the Socket.IO android library in perfect and flawless way you should read further.
There are three steps for implementing SOcket.IO Android Client library.

0. Initialise the Socket
1. Connect the socket to the server
2. Start emitting events or listening events

Many a times when we use Socket.IO the problems generally faced are

1-Incorrect initialisation and it gives NullPointerExecption.

2- The proper event could not be emitted and listened as the socket is not connected.

To avoid this try the following approach.

Very first step Add the following dependency in your app level build.gradle file

implementation ‘com.github.nkzawa:socket.io-client:0.5.2'

#0. Initialising the socket

To intialise the socket create an <name-of your application> class which extends Application class.

See the code snippet below

import android.app.Application;
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;
import java.net.URISyntaxException;
public class RatKiller extends Application {
private Socket mSocket;
private static final String URL = "http://yoururl.com";
@Override
public void onCreate() {
super.onCreate();
try {
mSocket = IO.socket(URL);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public Socket getmSocket(){
return mSocket;
}
}

Here in the application class, declare a private variable socket which is we are going to use as a reference you know.
The helper method getmSocket() will return the socket instance which we can use in our whole project.

#1.Connecting the socket

In order to connect the socket to server we need to use the connect() method on the socket instance returned from getmSocket() method.
Inside your MainActivity or any activity, add the following code in onCreate() method.

public class MainActivity extends AppCompatActivity {private Socket mSocket;@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RatKiller app = (RatKiller)getApplication();
mSocket = app.getmSocket();
//
//
//...
}

To check whether connection is established or not you can check by using connected() method.

if (mSocket.connected()){
Toast.makeText(MainActivity.this, "Connected!!",Toast.LENGTH_SHORT).show();
}

#2. Listen or Emit event

To emit event you can use emit() method.The emit() triggers an event on the server which you are going to implement as a button click or any actions response.

button.setOnCLickListener(view->mSocket.emit(“kill”,poisonObject));

To listen specific events sent by server, we use on() method. The on() method opens a channel provided and receives the response from server.

mSocket.on("rat_data", new Emitter.Listener() {
@Override
public void call(Object... args) {
JSONObject data = (JSONObject)args[0];
//here the data is in JSON Format
//Toast.makeText(MainActivity.this, data.toString(), Toast.LENGTH_SHORT).show();
}
});

Sometimes you need to listen the response of certain events which client/app is going to trigger either via button click or any action triggered etc.
In such cases, we can call the on() method over emit() method. The emit() method will trigger some event on specific route/channel and the on() will immediately listen the response send by the server.
You can achieve this by doing something like

mSocket.emit("get_rat_data").on("rat_data", new Emitter.Listener() {
@Override
public void call(Object... args) {
JSONObject data = (JSONObject)args[0];
//data is in JSOn format}
});

Data/Payload over request

The request payload or request body data must be send in JSON format to socket. The JSON Object is the input parameter of emit() method. The Java’s JSONObject and JSONArray class helps us to construct a JSON body format of the data.
You can do this as

JSONArray poisonArray = new JSONArray();
poisonArray.put(1);
poisonArray.put(2);
JSONObject poisonObject = new JSONObject();
try {

poisonObject.put("poisons",poisonArray);
} catch (JSONException e) {
e.printStackTrace();
}

Implementing the UI

Every time when you receive the data as a response from the server, you need to update your UI. To update the UI using received data we need to perform all the UI bind logic on runOnUiThread() method.

The call() method from Emmiter.Listener{…} used to work on a background thread. If you try to call the UI specific method inside the call, it’ll blow up by blasting our favourite Runtime Exceptions.
You can achieve this by calling a runOnUiThread(Runnable r) method.

mSocket.emit("kill",poisonObject).on("rat_data", new Emitter.Listener() {
@Override
public void call(Object... args) {
JSONObject data = (JSONObject)args[0];
//data is in JSOn format
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "Haha !! All rats are killed !", Toast.LENGTH_SHORT).show(); ratTextView.setText("0"); //whatever your UI logic
}
});
}
});

And done the problem is solved now. Yeah…I know! I am going to kill those Rats running everywhere on the floor.

--

--

Responses (15)