Quick Guide to Socket in Android

Socket.IO

Socket.IO is a JavaScript library for realtime internet applications. It permits real-time, bi-directional communication between internet shoppers and servers. it's 2 parts: a client-side library that runs within the browser, and a server-side library for node.js.

It provides more options, as well as broadcasting to multiple sockets, storing information related to every client, and asynchronous I/O.


Socket.IO Features

Socket.IO provides the flexibility to implement time period analytics, binary streaming, instant electronic communication, and document collaboration.

Socket.IO handles the connection transparently. It will automatically upgrade to WebSocket if possible. This requires the programmer to only have Socket.IO knowledge.

Introduction:-            
The application is based on chatting using SocketIO.The application code will help you to use Socket.Io in your android application.

The application provides below functionality:-

1) Sending Messages to all users.
2) Notify when the user leaves or joins the room.
3) Indicates if the user starts typing.


Adding the Dependencies:-

First, you need to install the Socket.IO with Gradle.

Add the below line in your build.gradle file:-

dependencies {
   compile 'com.github.nkzawa:socket.io-client:0.3.0'
}


Permissions Needed:-
     
You must give the internet permission to AndroidManifest.xml.

    <uses-permission android:name="android.permission.INTERNET" />


How to use socket in Activity and Fragment:-

First, you need to create an object of the Socket object.

      private Socket socket;

      @Override
      public void onActivityCreated(@Nullable Bundle savedInstanceState) {
              super.onActivityCreated(savedInstanceState);

                    try {
                         socket = IO.socket("http://41.185.91.27:3001"); //replace the URL
                         socket.on(Socket.EVENT_CONNECT, onConnect);
                         socket.on(Socket.EVENT_DISCONNECT, onDisconnect);
                         socket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
                         socket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
                         socket.on("getActiveUsers", socketGetActiveUserListner);
                         socket.on("addMeToRoom", socketAddMeToRoomListner);
                         socket.on("newMessage",newMessageListner);
                         socket.connect();    //Connect socket to server
                  } catch (URISyntaxException e) {
                        e.printStackTrace();
                 }

        }

Using socket.connect() we are going to connect through the server. Different type of listeners is provided by the Socket.IO and we can use that using socket.on() method like above.

    socket.on() method attach the listener which automatically called.

    Socket.EVENT_CONNECT         - Call when the connection is successfully created.
    Socket.EVENT_DISCONNECT      - Call when the connection is terminated.
    Socket.EVENT_CONNECT_ERROR   - Call when any error occurs.
    Socket.EVENT_CONNECT_TIMEOUT - Call if a timeout occurs.

You can also add a custom listener like getActiveUser to get all active user and addMeToRoom to add in a specific room.


Emitting events:-
                       
socket.emit() is used to send the message.

              @Override
              public void onActivityCreated(@Nullable Bundle savedInstanceState) {
                    super.onActivityCreated(savedInstanceState);

                    String message = et_message.getText().tostring();
                    socket.emit("newMessage",message);
              }


Listener:-

Create the listeners to get different events callback and perform tasks accordingly.

      private Emitter.Listener onDisconnect = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            if (getActivity() != null)
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                          
                           //perform anything

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
        }
    };

 onDisconnect call if the connection is terminated.

    private Emitter.Listener onConnectError = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
           
            //perform anything

        }
    };

    onConnectError call if any error occur.


    private Emitter.Listener onConnect = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {

            if (getActivity() != null)
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                      
                       //perform any task

                    }
                });
        }
    };

  onConnect call if the connection is successfully created.



 

Comments