I am currently using okhttp for network calls. I also need websocket so I made it like this:
public class WebSocketService extends Service implements WebSocketListener {
private static final String TAG = "WebSocketService";
private static final String BASE_URL = "ws://192.168.1.39:8080/websocket";
public static final int MSG_RESPONSE = 1;
public static final int MSG_HELLO = 2;
Messenger msger = new Messenger(new MessageHandler());
private WebSocket webSocket;
private boolean mWebSocketOpened = false;
private Messenger replyToMsngr;
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "service oncreate");
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(0, TimeUnit.NANOSECONDS)
.connectTimeout(15000, TimeUnit.MILLISECONDS)
.retryOnConnectionFailure(true)
.build();
Request request = new Request.Builder().url(BASE_URL).build();
WebSocketCall webSocketCall = WebSocketCall.create(okHttpClient, request);
webSocketCall.enqueue(this);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "onBind");
return msger.getBinder(); //using Messenger
}
@Override
public boolean onUnbind(Intent intent) {
Log.i(TAG, "onUnbind");
stopSelf();
return super.onUnbind(intent);
}
@Override
public void onOpen(WebSocket webSocket, Response response) {
Log.i(TAG, "On Open"+response.toString());
this.webSocket = webSocket;
mWebSocketOpened = true;
sendMessage(data);
}
@Override
public void onFailure(IOException e, Response response) {
Log.i(TAG, "onFailure " + e.getMessage());
e.printStackTrace();
mWebSocketOpened = false;
}
@Override
public void onMessage(ResponseBody message) throws IOException {
byte[] bytes = message.bytes();
if(message.contentType()==WebSocket.TEXT){
String newString = new String(bytes);
Message msg = Message.obtain(null, MSG_RESPONSE, 0,0);
msg.replyTo = replyToMsngr;
Bundle bundle = new Bundle();
bundle.putString("rec", newString);
msg.setData(bundle);
try {
replyToMsngr.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
message.close();
}
@Override
public void onPong(Buffer payload) {
Log.i(TAG, "onPong");
}
@Override
public void onClose(int code, String reason) {
mWebSocketOpened = false;
}
public class WebSocketBinder extends Binder{
public WebSocketService getService() {
// Return this instance of LocalService so clients can call public methods
return WebSocketService.this;
}
}
public void sendMessage(String msg){
Log.i(TAG, "sendMessage : "+msg);
if(mWebSocketOpened & webSocket!=null){
try {
RequestBody requestBody = RequestBody.create(WebSocket.TEXT, msg);
webSocket.sendMessage(requestBody);
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
}else{
Log.e(TAG, "socket not connected");
}
}
//test func
public int getRandomNumber(){
return new Random().nextInt(100);
}
public class MessageHandler extends android.os.Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_RESPONSE:
Bundle data = msg.getData();
replyToMsngr = msg.replyTo;
WebSocketService.this.sendMessage(data.getString("rec", "No data"));
break;
case MSG_HELLO:
Toast.makeText(getApplicationContext(), "heelo", Toast.LENGTH_SHORT).show();
break;
default:
super.handleMessage(msg);
}
}
}
}
But what I need to do is to be able to use STOMP in the web socket like in the example/library https://github.com/NaikSoftware/StompProtocolAndroid
if there is any way/ example to use okhttp along with stomp, it would help me if you mentioned. Also if the successful implementation of websocket with above mentioned library is needed here is how I implemented it.
public class TestActivity extends AppCompatActivity {
private static final String TAG = "testactivity";
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.ettext)
EditText ettext;
@BindView(R.id.content_test)
RelativeLayout contentTest;
@BindView(R.id.fab)
FloatingActionButton fab;
private StompClient mStompCLient;
private static final String BASE_URL = "ws://192.168.1.39:8080/websocket";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
ButterKnife.bind(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mStompCLient = Stomp.over(WebSocket.class, BASE_URL);
mStompCLient.topic("/topic/greetings").subscribe(topicMessage -> {
Log.d(TAG, topicMessage.getPayload());
});
mStompCLient.send("/app/hello", "{\"userName\":\"abcd\"}").subscribe();
mStompCLient.lifecycle().subscribe(lifecycleEvent -> {
switch (lifecycleEvent.getType()) {
case OPENED:
Log.d(TAG, "Stomp connection opened");
break;
case ERROR:
Log.e(TAG, "Error", lifecycleEvent.getException());
break;
case CLOSED:
Log.d(TAG, "Stomp connection closed");
break;
}
});
mStompCLient.connect();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
JSONObject object = new JSONObject();
try {
object.put("name", ettext.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
Log.i(TAG, "send data : "+ object.toString());
mStompCLient.send("/app/hello", object.toString()).subscribe();
}
});
}
@Override
protected void onStop() {
super.onStop();
disconnectStomp();
}
private void disconnectStomp() {
mStompCLient.disconnect();
}
}
It would also help if anyone can mention the stomp examples using okhttp websocket.
You can now call Stomp.over(okhttp3.WebSocket.class)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With