Working with Socket.io in Android

divyesh mali
3 min readMar 25, 2019
plug into the socket.

Every one knows what is socket but they don’t find the good way to implement or good examples for implementations. So finally i concluded to publish blog on Socket for Android.If you want to know more and excited for exploring what is socket you can find here.

Socket.IO provides you real-time bidirectional event based communication,which is very suitable for multiplayer games or real time communication.Socket.IO back-end in Node.js and easy to implement for back-end,there are lot’s of examples also available.But what in Android?

Socket.IO is connection are established even in presence of proxies and load balance.Actually Socket.IO is not a WebSocket implementation. It’s only user for transport.Socket.IO needed on both server and client side.Socket.IO provides the real-time communication for server and client.Here Both server and client can emit and listen their calls.Server also can trigger the event on specific route which are listened by their subscribers.Means client which has putted their listener for particular events.

Java also provides built in Socket.which is rich of many features and lot’s stuffs are there.

  1. Socket.IO Android-Java
  2. Naoyuki Kanezawa Android Socket.IO

And there another library available by Naoyuki Kanezawa, having their blog for socket.io by nkzawa. Specially i would recommend you to use this one, B‘cas it provide easy and simple implementation.Provides reliability,Auto-re connection support,dis-connection detection,binary,multiplex,room this all are supported.

Just in few steps you get your socket.io done.Let’s see the basic steps 😄.

Add dependency to app level build.gardle file

//app/build.gradle
dependencies {

compile ‘com.github.nkzawa:socket.io-client:0.3.0’
}

please don’t forget to add internet permission to AndroidManifest.xml

<!-- app/AndroidManifest.xml -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
...
</manifest>

Socket Initialization

Create general class which will initialize socket instance and it will be used every where in project with URL as shown below.

public class SocketInstance extends Application {
private Socket iSocket;
private static final String URL = "http://your_socket_connection_url.com";
@Override
public void onCreate() {
super.onCreate();
try { IO.Options opts = new IO.Options();
opts.query = "auth_token=" + authToken;
iSocket = IO.socket(URL, opts);

} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public Socket getSocketInstance(){
return iSocket;
}
}

As shown above in code we have first created Socket class instance and initialized.One question will arise in your mind why we have used IO.Option😕.

So for now it’s just for adding authentication or need to pass some extra parameters with url we can add like this.

Socket Connection to server 😍

So now we only just need to call the connect() method as shown in below code.So we will create Socket instance and get socket instance from general class by getSocketInstance() method which we created before.

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SocketInstance instance = (SocketInstance)getApplication();
mSocket = instance.getSocketInstance()
mSocket.connect();
}

That’s it 😃

Almost we have done, but now we need to check whether Socket has connected or not? 😕

Don’t worry we have method to check weather connection done or not.

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

Emit and Listen Events

For sending message in string or data of block like JSON and it also support binary data.

sendButton.setOnCLickListener{
mSocket.emit(“EventName”,dataObject));
}

For getting instant data from the server we need to use on() method to receive data.

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

So now we can implement this code in chat Application for getting instance response.We can also use this for many other purpose.When we are using socket please don’t forget to add change on UI thread.

runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "Pikabooo Here you done.", Toast.LENGTH_SHORT).show();ratTextView.setText("0");//whatever your UI logic
}
});

There are lot’s of other method also there for getting status while connection done, connection dis-connected etc.

Ahha Last but not least please don’t forget to close the socket connection and remove the listener when you done. B’cas it will lead you to memory leaks.

@Override
public void onDestroy() {
super.onDestroy();

mSocket.disconnect();
mSocket.off("event_name", Object);
}

Okay that’s it for now.See you later with some new stuffs.

--

--