Hello,
In this blog I am going to explain how you can connect with Web Socket from your Android App using OkHttp. This will be useful when you want to send some data real time from your Android app to Web app.
First add following line in your build.gradle file dependencies.
implementation 'com.squareup.okhttp3:okhttp:3.11.0'
Now let the gradle build and sync. Next we will make a class which extends WebSocketListener from OkHttp3 and a new class and name it MyWebSocketListener.java and add following code to it.
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;
public final class MyWebSocketListener extends WebSocketListener {
private static final int NORMAL_CLOSURE_STATUS = 5000;
public MyWebSocketListener() {
}
@Override
public void onOpen(WebSocket webSocket, Response response) {
webSocket.close(NORMAL_CLOSURE_STATUS, "Exit");
}
@Override
public void onMessage(WebSocket webSocket, String text) {
//String Meesage received
}
@Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
//Meesage received in form of binary data
}
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
webSocket.close(NORMAL_CLOSURE_STATUS, null);
//Closing socket
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
t.printStackTrace();
}
}
Now we have listener created. Let's create client and attach it to Web Socket and Listener.
val listener = MyWebSocketListener()
val webSocket = OkHttpClient.Builder().build().newWebSocket(request, listener)
That's it, now you can use this instance to send or receive message.
No comments:
Post a Comment