How to integrate Websocket in android application

Posted By : Keshav Gupta | 01-Sep-2017

In this we will use java websockets.

Step1:add following dependency in app/build.gradle and sync the project.

dependencies {
  compile "org.java-websocket:Java-WebSocket:1.3.0"
}

Step 2: Now move to activity class where you wanted to implement behaviour for socket.

Create a instance for WebsocketClient like this as a class variable:

private WebSocketClient mWebSocketClient;

Step 3: Now I have created a method which incorporate object creation and listeners which give callback regarding status of WebSocket.put this method in onCreate() of activity class.

private void connectToSocket() {
    URI uri;
    try {
        uri = new URI(ws:urlname);
    } catch (URISyntaxException e) {
        e.printStackTrace();
        return;
    }
    mWebSocketClient = new WebSocketClient(uri, new Draft_17()) {
        @Override
        public void onOpen(ServerHandshake serverHandshake) {
            Logger.LogInfo("Websocket", "Opened");
        }
        @Override
        public void onMessage(String s) {
            final String message = s;
        }
        @Override
        public void onClose(int i, String s, boolean b) {
            Logger.LogInfo("Websocket", "Closed " + s);
        }
        @Override
        public void onError(Exception e) {
            Logger.LogInfo("Websocket", "Error " + e.getMessage());
        }
    };
    mWebSocketClient.connect();
}

In above method first line of generated a URI by parsing given string and  WebSocketClient instance is created and sets it to the connect to the specified URI. The channel does not attampt to connect automatically. You must call connect first to initiate the socket connection

Callback of socket connection report can be check in listener which override method:

onOpen():  if websocket is connected then Log window will display connected info.

onClose(): if websocket connection is disconnected due to internet failure or external call for disconnection,then Log window will display                         such info. 

onError(): if any error comes in websocket operation that can be displayed using this method.It will show certain error message.

connect(): it connects the websocket object to specified uri.

There is another one method:

connectBlocking():
Same as connect but blocks until the websocket connected or failed to do so. Returns whether it succeeded or not.It throws InterruptedException which needs to be handled.

SendMessage:

Now we can send a message to server using send() method.I have defined a method in which send functionality is being carried out

private void sendHitToAdmin() {
    try {
        mWebSocketClient.send(Hello World);
    } catch (NotYetConnectedException e) {
        e.printStackTrace();
    }
}

Receive Message:

Theres is one more method in listener overrided methods:

onMessage(String s):

This method will contain messages received from server.You can print messages like this on any UI.Edit above method like this.

@Override
    public void onMessage(String s) {
      final String message = s;
      runOnUiThread(new Runnable() {
        @Override
        public void run() {
          TextView textView = (TextView)findViewById(R.id.uiview);
          textView.setText(textView.getText() + "\n" + message);
        }
      });
    }

 

 

 

 

 

 

 

 

 

 

 

About Author

Author Image
Keshav Gupta

Keshav Gupta is Android Developer in Oodles, he always look forward for new tasks and new things to learn more.

Request for Proposal

Name is required

Comment is required

Sending message..