Friday 29 July 2016

Android - Websocket

Hi,

This is tutorial how to integrate WebSocket with Android. We need 3 different files:
  1. WebSocketTask.java
    • import android.content.Context;
      import android.os.AsyncTask;
      import android.util.Log;
      
      import org.java_websocket.client.WebSocketClient;
      import org.java_websocket.handshake.ServerHandshake;
      import org.json.JSONException;
      import org.json.JSONObject;
      
      import java.net.URI;
      import java.net.URISyntaxException;
      import java.util.concurrent.ExecutionException;
      
      public class WebSocketTask extends AsyncTask {
          public boolean isConnected = false;
      
          private WebSocketClient webSocketClient;
          private ICallback iCallback;
      
          public WebSocketTask(Context context) {
              this.iCallback = (ICallback) context;
          }
      
          @Override    protected WebSocketClient doInBackground(String... params) {
              final String channel = params[0];
              URI uri;
      
              try {
                  uri = new URI("ws://your-websocket-server.com");
              } catch (URISyntaxException e) {
                  e.printStackTrace();
                  return null;
              }
      
              webSocketClient = new WebSocketClient(uri) {
                  @Override            public void onOpen(ServerHandshake serverHandshake) {
                      isConnected = true;
      
                      JSONObject message = new JSONObject();
                      try {
                          message.put("channel", channel);
                          message.put("subscribe", true);
                      } catch (JSONException e) {
                          e.printStackTrace();
                      }
                      webSocketClient.send(message.toString());
                  }
      
                  @Override            public void onMessage(String s) {
                      try {
                          JSONObject data = new JSONObject(s);
      
                          if (data.has("channel")) {
                              iCallback.webSocketCallback(data);
                          }
                      } catch (JSONException e) {
                          e.printStackTrace();
                      } catch (InterruptedException e) {
                          e.printStackTrace();
                      } catch (ExecutionException e) {
                          e.printStackTrace();
                      }
                  @Override            public void onClose(int i, String s, boolean b) {
                      Log.i("Websocket", "Closed " + s);
                  }
      
                  @Override            public void onError(Exception e) {
                      Log.i("Websocket", "Error " + e.getMessage());
                  }
              };
              webSocketClient.connect();
      
              return webSocketClient;
          }
      
          public void sendMessage(WebSocketClient client, String channel, JSONObject message) throws JSONException {
              JSONObject data = new JSONObject();
      
              data.put("channel", channel);
              data.put("data", message);
      
              client.send(data.toString());
          }
      }
      
  2. ICallback.java
    • import org.json.JSONException;
      import org.json.JSONObject;
      
      import java.util.concurrent.ExecutionException;
      
      public interface ICallback {
          void webSocketCallback(JSONObject data) throws JSONException, ExecutionException, InterruptedException;
      }
      
  3. MainActivity.java
    • import android.os.Bundle;
      import android.os.Handler;
      import android.support.v7.app.AppCompatActivity;
      import android.util.Log;
      
      import org.java_websocket.client.WebSocketClient;
      import org.json.JSONException;
      import org.json.JSONObject;
      
      import java.util.concurrent.ExecutionException;
      
      public class MainActivity extends AppCompatActivity implements ICallback {
      
          WebSocketTask webSocketTask;
          WebSocketClient webSocketBattleChannel;
      
          String myChannelKey = "my-channel";
      
          @Override
          protected void onDestroy() {
              super.onDestroy();
      
              webSocketTask.cancel(true);
          }
      
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
      
              // New websocket task
              webSocketTask = new WebSocketTask(this);
              try {
                  // Connect to websocket channel
                  webSocketBattleChannel = webSocketTask.execute(myChannelKey).get();
              } catch (InterruptedException e) {
                  e.printStackTrace();
              } catch (ExecutionException e) {
                  e.printStackTrace();
              }
          }
      
          // Send message to other users
          private void sendMessage(JSONObject data, boolean isDoubleSend) throws JSONException {
              final JSONObject message = data;
      
              // Check the websocket connection
              if (webSocketTask.isConnected) {
                  webSocketTask.sendMessage(webSocketBattleChannel, myChannelKey, message);
              }
      
              // Try to double send in some case of connection lost
              if (webSocketTask.isConnected && isDoubleSend) {
                  Handler handler = new Handler();
                  handler.postDelayed(new Runnable() {
                      public void run() {
                          try {
                              webSocketTask.sendMessage(webSocketBattleChannel, myChannelKey, message);
                          } catch (JSONException e) {
                              e.printStackTrace();
                          }
                      }
                  }, 1000);
              }
          }
      
          // Listen to other users send message
          @Override
          public void webSocketCallback(JSONObject message) throws JSONException {
              // Get data in the message
              final JSONObject data = message.getJSONObject("data");
      
              // To make sure we can modify view
              runOnUiThread(new Runnable() {
                  @Override
                  public void run() {
                      Log.d("WebSocket", data.toString());
                  }
              });
          }
      }
      

Done. We simply use it by 2 functions:
  1. sendMessage:
    • Send message to who listen to channel: my-channel
  2. webSocketCallback:
    • Listen to channel: my-channel
Good luck!

No comments:

Post a Comment