I am currently working on an GPS based project, I am currently using volley to receive data from web but recently they plan to upgrade the services with real time data. so web developers have programmed the server using websocket, and for browser application they said, they are using stomp.js protocol for retrieving data from server. They requested me to retrieve data from their server (Real Time Data) use any, but I don't know what will be the best suitable method to get real time data from websocket. I found one example from github https://github.com/NaikSoftware/StompProtocolAndroid but it's not enough for me to learn, and documentation for using stomp are not enough on internet. I hope there could be better implementation in android.
Please any help and suggestion would be appreciated. Please don't mention me firebase because I have already mentioned them about firebase and they refused to use it. Please guys help me, suggest me or give me one good example to simply retrieve data from websocket server using volley..
First, you need to copy your web browser's header to here and use json. dumps to convert it into the string format. After that, create the connection to the server by using create_connection . Then, perform the handshake by sending the message, and you will be able to see the data on your side.
WebSocket approach is ideal for real-time scalable application, whereas REST is better suited for the scenario with lots of getting request. WebSocket is a stateful protocol, whereas REST is based on stateless protocol, i.e. the client does not need to know about the server and the same hold true for the server.
Once the original connection has been closed, you need to create a new websocket object with new event listeners: var SERVER = 'ws://localhost:8080' var ws = new WebSocket(SERVER) ws. onmessage = function(e){ console. log('websocket message event:', e) } ws.
The WebSocket is closed before the connection is established error message indicates that some client code, or other mechanism, has closed the websocket connection before the connection was fully established.
My answer is based on the comments in this question. Don't have enough information on the question so I am writing 2 solution for your question
Solution 1 - Without using Stomp Implementation- Simple websocket
This is a simple Websocket implementation. for this you can use koush/AndroidAsync library
implement this project into your project
dependencies {
compile 'com.koushikdutta.async:androidasync:2.+'
}
then connect to Websocket server
String url="ws://172.17.1.54:8000/";
AsyncHttpClient.getDefaultInstance().websocket(url, "my-protocol", new WebSocketConnectCallback() {
@Override
public void onCompleted(Exception ex, WebSocket webSocket) {
if (ex != null) {
ex.printStackTrace();
return;
}
webSocket.setStringCallback(new StringCallback() {
public void onStringAvailable(String s) {
System.out.println("I got a string: " + s);
}
});
webSocket.setDataCallback(new DataCallback() {
public void onDataAvailable(DataEmitter emitter, ByteBufferList byteBufferList) {
System.out.println("I got some bytes!");
// note that this data has been read
byteBufferList.recycle();
}
});
}
});
here setStringCallback() & setDataCallback() will receive your real time update.
You can also use codebutler/android-websockets library for this.
Solution 2: With use Stomp implementation
For this you can use Gozirra java library for solving this problem. You can download client library.then put it into your libs folder.
For connecting to your server
Client c = new Client("server url", port, "login", "password");
Create a listener for the updates
Listener listener=new Listener() {
@Override
public void message(Map map, String s) {
//Do your stuff
}
};
Then Subscribe to your topic messages
c.subscribe("foo-channel", listener);
If you want to unsubscribe you can use below code
c.unsubscribe("foo-channel", listener); // Unsubscribe only one listener
or
c.unsubscribe("foo-channel"); // Unsubscribe all listeners
For disconnecting client
c.disconnect();
I didn't test this with a real server .But I think this will work.Please let me know if it solves your problem
Solution 3
As you mention the library https://github.com/NaikSoftware/StompProtocolAndroid You can use this. simplify version is as follows
Add maven link into your project level gradle
repositories {
maven { url "https://jitpack.io" }
}
Add dependency in your module level gradle
implementation 'com.github.NaikSoftware:StompProtocolAndroid:1.1.5'
implementation 'org.java-websocket:Java-WebSocket:1.3.0'
Then use following code for getting message
StompClient mStompClient = Stomp.over(WebSocket.class, "ws://10.0.2.2:5000/");
mStompClient.topic("/topic/general").subscribe(new Action1<StompMessage>() {
@Override
public void call(StompMessage stompMessage) {
Log.e(TAG, stompMessage.getPayload());
}
});
mStompClient.lifecycle().subscribe(new Action1<LifecycleEvent>() {
@Override
public void call(LifecycleEvent lifecycleEvent) {
switch (lifecycleEvent.getType()) {
case OPENED:
Log.e(TAG, "Stomp connection opened");
break;
case ERROR:
Log.e(TAG, "Error", lifecycleEvent.getException());
break;
case CLOSED:
Log.e(TAG, "Stomp connection closed");
break;
}
}
});
mStompClient.connect();
Use Square's OkHttp library.
Add this dependency to your build gradle
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
Use below class for listening of webshockts
public class SocketListner extends WebSocketListener {
private Mediator mediator;
private static final int CLOSURE_STATUS = 1000;
private WebSocket webSocket = null;
public SocketListner(Mediator mediator) {
this.mediator = mediator;
}
@Override
public void onOpen(WebSocket webSocket, Response response) {
super.onOpen(webSocket, response);
this.webSocket = webSocket;
mediator.onConnected(webSocket, response);
}
public void sendMsg(String msg) {
if (webSocket != null)
webSocket.send(msg);
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, @Nullable Response response) {
mediator.onFailure(webSocket, t.getLocalizedMessage());
AppCons.printTag("Failure :", t.getMessage());
}
@Override
public void onClosed(WebSocket webSocket, int code, String reason) {
mediator.closingOrClosed(true, webSocket, reason, code);
AppCons.printTag("Closed :", reason);
}
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
mediator.closingOrClosed(false, webSocket, reason, code);
AppCons.printTag("Closing :", reason);
}
@Override
public void onMessage(WebSocket webSocket, String text) {
mediator.getMessage(text);
}
public interface Mediator {
void onConnected(WebSocket webSocket, Response response);
void getMessage(String msg);
void onFailure(WebSocket webSocket, String reason);
void closingOrClosed(boolean isClosed, WebSocket webSocket, String reason, int code);
}
public WebSocket getWebSocket() {
return webSocket;
}
}
Use the below code for accessing the data through shocket
private OkHttpClient client;
private SocketListner listner;
private void startShocketConnection() {
client = new OkHttpClient.Builder().readTimeout(3, TimeUnit.SECONDS).build();
listner = new SocketListner(new SocketListner.Mediator() {
@Override
public void onConnected(WebSocket webSocket, Response response) {
Log.d("Connected :", response.toString());
}
@Override
public void getMessage(String msg) {
try {
Log.d("Received", msg);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(WebSocket webSocket, String reason) {
//reconnect when failure with server
Log.d("Failure :", reason);
}
@Override
public void closingOrClosed(boolean isClosed, WebSocket webSocket, String reason, int code) {
Log.d("ClosingOrClosed :", isClosed ? "Closed" : "closing");
}
});
Request request = new Request.Builder()
.url("your shocket url")
.build();
client.newWebSocket(request, listner);
}
private void closeSocket() {
try {
listner.getWebSocket().cancel();
listner.getWebSocket().close(1000, "Good bye !");
if ((response != null)) {
client.dispatcher().executorService().shutdown();
client.connectionPool().evictAll();
response.close();
}
} catch (Exception e) {
e.printStackTrace();
}
response = null;
}
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