Sie sind auf Seite 1von 13

Set up a Stomp client in android with Spring framework in server side - Stack Overflow

sign up log in tour help

Questions Jobs Documentation Beta Tags Users Badges Ask Question

x Dismiss

Join the Stack Overflow Community

Stack Overflow is a community of 6.6 million


programmers, just like you, helping each other.
Join them; it only takes a minute:

Sign up

Set up a Stomp client in android with Spring framework in server side

asked 2 years ago


I am developing an android application that exchanges data with a jetty server configured in
Spring. To obtain a more dynamic android application, i am trying to use WebSocket protocol with viewed 8011 times
7 Stomp messages.
active 21 days ago
In order to realize this stuff, i config a web socket message broker in spring :

@Configuration BLOG
//@EnableScheduling
4
@ComponentScan( Stack Overflow Podcast #100 - Jeff
basePackages="project.web", Atwood Is Back! (For Today)
excludeFilters = @ComponentScan.Filter(type= FilterType.ANNOTATION, value =
Configuration.class) Developers without Borders: The
) Global Stack Overflow Network
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/message");
http://stackoverflow.com/questions/24346068/set-up-a-stomp-client-in-android-with-spring-framework-in-server-side[01/02/2017 00:56:53]
Set up a Stomp client in android with Spring framework in server side - Stack Overflow
config.setApplicationDestinationPrefixes("/app"); Get the weekly newsletter! In it, you'll get:
}
The week's top questions and answers
@Override Important community announcements
public void registerStompEndpoints(StompEndpointRegistry registry) { Questions that need answers
registry.addEndpoint("/client");
}
} Sign up for the newsletter

and a SimpMessageSendingOperations in Spring controller to send message from server to client : see an example newsletter

@Controller
public class MessageAddController { Linked
private final Log log = LogFactory.getLog(MessageAddController.class);
0
private SimpMessageSendingOperations messagingTemplate;
How connect android device to Spring websocket
private UserManager userManager; server

private MessageManager messageManager; Related


@Autowired 1
public MessageAddController(SimpMessageSendingOperations messagingTemplate,
Spring 4 STOMP Websockets - How to realise
UserManager userManager, MessageManager messageManager){
Multichannel
this.messagingTemplate = messagingTemplate;
this.userManager = userManager; 1
this.messageManager = messageManager;
} Connect with a Stomp PHP library to Spring
websockets (stomp)
@RequestMapping("/Message/Add")
@ResponseBody 2
public SimpleMessage addFriendship( Communication relationship when using
@RequestParam String content, SimpleBrokerMessageHandler - STOMP Spring
@RequestParam Long otherUser_id
){ 1
if(log.isInfoEnabled()) Multiple rooms in Spring using STOMP
log.info("Execute MessageAdd action");
SimpleMessage simpleMessage; 4

try{ Spring 4 STOMP Websockets Heartbeat


User curentUser = userManager.getCurrentUser();
4
User otherUser = userManager.findUser(otherUser_id);
stomp message acknowledgement from client
Message message = new Message();
message.setContent(content); 3
message.setUserSender(curentUser); Spring stomp web sockets client for android
message.setUserReceiver(otherUser);
1
messageManager.createMessage(message); STOMP in Spring WebSocket Lost Connection
before connected
When i test this configuration in a web browser with stomp.js, I haven't any problem : messages
are perfectly exchanged between web browser and Jetty server. The JavaScript code using for 0

http://stackoverflow.com/questions/24346068/set-up-a-stomp-client-in-android-with-spring-framework-in-server-side[01/02/2017 00:56:53]
Set up a Stomp client in android with Spring framework in server side - Stack Overflow
web browser test : Spring stomp over websocket client reconnects
causes a huge open file descriptors
var stompClient = null;
0
function setConnected(connected) { Stomp SockJs client + server Spring
document.getElementById('connect').disabled = connected;
document.getElementById('disconnect').disabled = !connected;
document.getElementById('conversationDiv').style.visibility = connected ?
Hot Network Questions
'visible' : 'hidden';
Why did Fernand stop escaping after he shot
document.getElementById('response').innerHTML = '';
Mercedes?
}
Drawbacks of participating in a conference boycott
function connect() {
stompClient = Stomp.client("ws://YOUR_IP/client"); How could immortal children age faster than
stompClient.connect({}, function(frame) { immortal adults?
setConnected(true); When does a player have to state they are
stompClient.subscribe('/message/add', function(message){ making a passive check?
showMessage(JSON.parse(message.body).content);
}); Should a player know their mount's exact HP?
});
more hot questions
}

function disconnect() {
stompClient.disconnect();
setConnected(false);
console.log("Disconnected");
}

function showMessage(message) {
var response = document.getElementById('response');
var p = document.createElement('p');
p.style.wordWrap = 'break-word';
p.appendChild(document.createTextNode(message));
response.appendChild(p);
}

Problems occur when i try to use stomp in Android with libraries like gozirra, activemq-stomp or
others : most of time, connection with server doesn't work. My app stop to run and, after a few
minutes, i have the following message in logcat : java.net.UnknownHostException: Unable to
resolve host "ws://192.168.1.39/client": No address associated with hostname , and i don't
understand why. Code using Gozzira library which manages the stomp appeal in my android
activity :

private void stomp_test() {


String ip = "ws://192.172.6.39/client";
int port = 8080;

String channel = "/message/add";


Client c;

http://stackoverflow.com/questions/24346068/set-up-a-stomp-client-in-android-with-spring-framework-in-server-side[01/02/2017 00:56:53]
Set up a Stomp client in android with Spring framework in server side - Stack Overflow
try {
c = new Client( ip, port, "", "" );
Log.i("Stomp", "Connection established");
c.subscribe( channel, new Listener() {
public void message( Map header, String message ) {
Log.i("Stomp", "Message received!!!");
}
});

} catch (IOException ex) {


Log.e("Stomp", ex.getMessage());
ex.printStackTrace();

} catch (LoginException ex) {


Log.e("Stomp", ex.getMessage());
ex.printStackTrace();
} catch (Exception ex) {
Log.e("Stomp", ex.getMessage());
ex.printStackTrace();
}

After some research, i found that most persons who want to use stomp over websocket with Java
Client use ActiveMQ server, like in this site. But spring tools are very simple to use and it will be
cool if i could keep my server layer as is it now. Someone would know how to use stomp java
(Android) in client side with Spring configuration in server side?

android spring websocket stomp

share improve this question


edited Feb 10 '15 at 9:46 asked Jun 21 '14 at 21:35

EPerrin95
264 4 12

you didn't talk about how you are managing threads. F.O.O Jul 17 '16 at 18:22

add a comment

3 Answers active oldest votes

My implementation of STOMP protocol for android (or plain java) with RxJava
https://github.com/NaikSoftware/StompProtocolAndroid. Tested on STOMP server with
http://stackoverflow.com/questions/24346068/set-up-a-stomp-client-in-android-with-spring-framework-in-server-side[01/02/2017 00:56:53]
Set up a Stomp client in android with Spring framework in server side - Stack Overflow

7 SpringBoot. Simple example (with retrolambda):

private StompClient mStompClient;

// ...

mStompClient = Stomp.over(WebSocket.class, "ws://localhost:8080/app/hello/websocket");


mStompClient.connect();

mStompClient.topic("/topic/greetings").subscribe(topicMessage -> {
Log.d(TAG, topicMessage.getPayload());
});

mStompClient.send("/app/hello", "My first STOMP message!");

// ...

mStompClient.disconnect();

Add the following classpath in project :

classpath 'me.tatarka:gradle-retrolambda:3.2.0'

Add the following thing in your app build.gradle :

apply plugin: 'me.tatarka.retrolambda'

android {
.............
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}

dependencies {
............................
compile 'org.java-websocket:Java-WebSocket:1.3.0'
compile 'com.github.NaikSoftware:StompProtocolAndroid:1.1.5'
}

All working asynchronously! You can call connect() after subscribe() and send() , messages
will be pushed to queue.

Additional features:

extra HTTP headers for handshake query (for passing auth token or other)
you can implement own transport for library, just implement interface ConnectionProvider
subscribe connection lifecycle events (connected, closed, error)
http://stackoverflow.com/questions/24346068/set-up-a-stomp-client-in-android-with-spring-framework-in-server-side[01/02/2017 00:56:53]
Set up a Stomp client in android with Spring framework in server side - Stack Overflow

For Example :

public class MainActivity extends AppCompatActivity {


private StompClient mStompClient;
public static final String TAG="StompClient";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button view = (Button) findViewById(R.id.button);


view.setOnClickListener(e-> new LongOperation().execute(""));

private class LongOperation extends AsyncTask<String, Void, String> {


private StompClient mStompClient;
String TAG="LongOperation";
@Override
protected String doInBackground(String... params) {

mStompClient = Stomp.over(WebSocket.class,
"ws://localhost:8080/app/hello/websocket");
mStompClient.connect();

mStompClient.topic("/topic/greetings").subscribe(topicMessage -> {
Log.d(TAG, topicMessage.getPayload());
});

mStompClient.send("/app/hello", "My first STOMP message!").subscribe();

mStompClient.lifecycle().subscribe(lifecycleEvent -> {
switch (lifecycleEvent.getType()) {

case OPENED:
Log.d(TAG, "Stomp connection opened");
break;

Add Internet permission in manifest.xml

<uses-permission android:name="android.permission.INTERNET" />

share improve this answer


edited Jan 10 at 9:22 answered May 14 '16 at 7:55

krishnan Nickolay Savchenko


1,428 1 13 24 399 3 11

http://stackoverflow.com/questions/24346068/set-up-a-stomp-client-in-android-with-spring-framework-in-server-side[01/02/2017 00:56:53]
Set up a Stomp client in android with Spring framework in server side - Stack Overflow

How do you reconnect with your library? Thanks. File Aug 9 '16 at 11:24

1 can't use it. everytime StompClient receive message, it always disconnected. Raizal Nov 9 '16 at 4:42

1 @Raizal call connect() method after subscibe Nickolay Savchenko Nov 9 '16 at 8:55

Its working.Thanks Nickolay Savchenko krishnan Jan 7 at 4:28

add a comment

I achieve to use stomp over web socket with Android and spring server.

6 To do such a thing, i used a web socket library : werbench (follow this link to download it). To
install, I used the maven command mvn install and i got back the jar in my local repository.
Then, I need to add a stomp layer on the basic web socket one, but i couldn't find any stomp
library in java which could manage stomp over web socket (I had to give up gozzira). So I create
my own one (with stomp.js like model). Don't hesitate to ask me if you want take a look at it, but i
realized it very quickly so it can not manage as much as stomp.js. Then, i need to realize an
authentication with my spring server. To achieve it, i followed the indication of this site. when i get
back the JSESSIONID cookie, I had just need to declare an header with this cookie in the
instantiation of a werbench web socket in my stomp "library".

EDIT : this is the main class in this library, the one which manage the stomp over web socket
connection :

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import android.util.Log;
import de.roderick.weberknecht.WebSocket;
import de.roderick.weberknecht.WebSocketEventHandler;
import de.roderick.weberknecht.WebSocketMessage;

public class Stomp {

private static final String TAG = Stomp.class.getSimpleName();

http://stackoverflow.com/questions/24346068/set-up-a-stomp-client-in-android-with-spring-framework-in-server-side[01/02/2017 00:56:53]
Set up a Stomp client in android with Spring framework in server side - Stack Overflow

public static final int CONNECTED = 1;//Connection completely established


public static final int NOT_AGAIN_CONNECTED = 2;//Connection process is ongoing
public static final int DECONNECTED_FROM_OTHER = 3;//Error, no more internet
connection, etc.
public static final int DECONNECTED_FROM_APP = 4;//application explicitely ask for
shut down the connection

private static final String PREFIX_ID_SUBSCIPTION = "sub-";


private static final String ACCEPT_VERSION_NAME = "accept-version";
private static final String ACCEPT_VERSION = "1.1,1.0";
private static final String COMMAND_CONNECT = "CONNECT";
private static final String COMMAND_CONNECTED = "CONNECTED";
private static final String COMMAND_MESSAGE = "MESSAGE";
private static final String COMMAND_RECEIPT = "RECEIPT";
private static final String COMMAND_ERROR = "ERROR";
private static final String COMMAND_DISCONNECT = "DISCONNECT";
private static final String COMMAND_SEND = "SEND";
private static final String COMMAND_SUBSCRIBE = "SUBSCRIBE";
private static final String COMMAND_UNSUBSCRIBE = "UNSUBSCRIBE";
private static final String SUBSCRIPTION_ID = "id";
private static final String SUBSCRIPTION_DESTINATION = "destination";
private static final String SUBSCRIPTION SUBSCRIPTION = "subscription";

This one is the Frame of a Stomp message :

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Frame {


// private final static String CONTENT_LENGTH = "content-length";

private String command;


private Map<String, String> headers;
private String body;

/**
* Constructor of a Frame object. All parameters of a frame can be instantiate
*
* @param command
* @param headers
* @param body
*/
public Frame(String command, Map<String, String> headers, String body){
this.command = command;
this.headers = headers != null ? headers : new HashMap<String, String>();
this.body = body != null ? body : "";
}

public String getCommand(){

http://stackoverflow.com/questions/24346068/set-up-a-stomp-client-in-android-with-spring-framework-in-server-side[01/02/2017 00:56:53]
Set up a Stomp client in android with Spring framework in server side - Stack Overflow
return command;
}

public Map<String, String> getHeaders(){


return headers;
}

public String getBody(){


return body;
}

This one is an object used to establish a subscription via the stomp protocol :

public class Subscription {

private String id;

private String destination;

private ListenerSubscription callback;

public Subscription(String destination, ListenerSubscription callback){


this.destination = destination;
this.callback = callback;
}

public String getId() {


return id;
}
public void setId(String id) {
this.id = id;
}

public String getDestination() {


return destination;
}

public ListenerSubscription getCallback() {


return callback;
}
}

At least, there are two interfaces used as the "Run" java class, to listen web socket network and a
given subscription canal

public interface ListenerWSNetwork {


public void onState(int state);
}

import java.util.Map;
public interface ListenerSubscription {

http://stackoverflow.com/questions/24346068/set-up-a-stomp-client-in-android-with-spring-framework-in-server-side[01/02/2017 00:56:53]
Set up a Stomp client in android with Spring framework in server side - Stack Overflow
public void onMessage(Map<String, String> headers, String body);
}

For more information, don't hesitate to ask me.

share improve this answer


edited Feb 10 '15 at 9:52 answered Jul 8 '14 at 9:08

EPerrin95
264 4 12

2 You should always post your solution. Anders Metnik Sep 15 '14 at 12:19

1 Could you please provide an example about how to subscribe to ws service? ismail Feb 9 '15 at 0:31

Hi, How do you manage to run Spring over Cross domain (mobile devices). I am implementing a solution
using Spring with Sockjs and JWT tokens but Sockjs fallback into iframe because (I think) the client is
running in a different domain. cardeol Apr 5 '16 at 21:15

add a comment

Perfect solution Eperrin thank you. I would like fill the complete solution e.g. in your
Activity/Service phase you call connection method of course doesn't in MainThread.
1
private void connection() { Map<String,String> headersSetup = new HashMap<String,String>();
Stomp stomp = new Stomp(hostUrl, headersSetup, new ListenerWSNetwork() { @Override public
void onState(int state) { } }); stomp.connect(); stomp.subscribe(new Subscription(testUrl,
new ListenerSubscription() { @Override public void onMessage(Map<String, String> headers,
String body) { } })); }

And be careful in websocket weberknecht library is bug in WebSocketHandshake class in


method verifyServerHandshakeHeaders is on the line 124 is check only
if(!headers.get("Connection").equals("Upgrade")) and when server send upgrade instead of
Upgrade you get error connection failed: missing header field in server handshake: Connection
you have to turn off ignore cases if(!headers.get("Connection").equalsIgnoreCase("Upgrade"))

share improve this answer


answered Mar 3 '15 at 16:18

horkavlna
1,884 1 9 12

http://stackoverflow.com/questions/24346068/set-up-a-stomp-client-in-android-with-spring-framework-in-server-side[01/02/2017 00:56:53]
Set up a Stomp client in android with Spring framework in server side - Stack Overflow
My server also have path to SEND messages (chat broker). So how can I send something to it with that
solution? udenfox Mar 31 '15 at 15:21

I will try explain solution for AsyncTask the same you can do it in Services. First you have to create
Activity/Fragment, after you call AsyncTask and in phase doInBackground you call my method connection
(in previous answered). And you have to import weberknecht library in your project because you call object
Stomp which exist in this library thos is everything. But be careful your server must support STOMP version
websocket horkavlna Mar 31 '15 at 15:39

Okay, I got It. Reading code a little bit carefully makes me understand. Thanks! udenfox Mar 31 '15 at
16:47

Don't forget send PING server, default implementation doesn't send PING and you can get EOF after few
doesn't send PING ...it depends implementation on server. horkavlna Nov 4 '15 at 14:42

add a comment

Your Answer

Sign up or log in Post as a guest

Sign up using Google Name

Sign up using Facebook


Email

Sign up using Email and Password

http://stackoverflow.com/questions/24346068/set-up-a-stomp-client-in-android-with-spring-framework-in-server-side[01/02/2017 00:56:53]
Set up a Stomp client in android with Spring framework in server side - Stack Overflow

Post Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged android spring websocket

stomp or ask your own question.

question feed

about us tour help blog chat data legal privacy policy work here advertising info developer jobs directory mobile contact us feedback

CULTURE /
TECHNOLOGY LIFE / ARTS SCIENCE OTHER
RECREATION

Stack Overflow Geographic Information Code Review Photography English Language & MathOverflow Meta Stack Exchange
Systems Usage
Server Fault Magento Science Fiction & Mathematics Stack Apps
Electrical Engineering Fantasy Skeptics
Super User Signal Processing Cross Validated (stats) Area 51
Android Enthusiasts Graphic Design Mi Yodeya (Judaism)
Web Applications Raspberry Pi Theoretical Computer Stack Overflow Talent
Information Security Movies & TV Travel Science
Ask Ubuntu Programming Puzzles &
Database Administrators Code Golf Music: Practice & Theory Christianity Physics
Webmasters
Drupal Answers more (7) Seasoned Advice English Language Chemistry
Game Development (cooking) Learners
SharePoint Biology
TeX - LaTeX Home Improvement Japanese Language
User Experience Computer Science
Software Engineering Personal Finance & Arqade (gaming)
Mathematica Money Philosophy
Unix & Linux Bicycles
Salesforce Academia more (3)
Ask Different (Apple) Role-playing Games
ExpressionEngine more (8)
WordPress Development Answers Anime & Manga

Cryptography Motor Vehicle


Maintenance & Repair

more (17)

http://stackoverflow.com/questions/24346068/set-up-a-stomp-client-in-android-with-spring-framework-in-server-side[01/02/2017 00:56:53]
Set up a Stomp client in android with Spring framework in server side - Stack Overflow
site design / logo 2017 Stack Exchange Inc; user contributions licensed under cc by-sa 3.0 with attribution required
rev 2017.1.31.24871

http://stackoverflow.com/questions/24346068/set-up-a-stomp-client-in-android-with-spring-framework-in-server-side[01/02/2017 00:56:53]

Das könnte Ihnen auch gefallen