I am using this guide to implement a simple Stomp client:
WebSocketClient webSocketClient = new StandardWebSocketClient();
WebSocketStompClient stompClient = new WebSocketStompClient(webSocketClient);
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.afterPropertiesSet();
stompClient.setTaskScheduler(taskScheduler); // for heartbeats
stompClient.setMessageConverter(new StringMessageConverter());
StompSessionHandler sessionHandler = new MySessionHandler();
stompClient.connect("ws://server/endpoint", sessionHandler);
// WAITING HERE
When connection completes it's supposed to report to MySessionHandler
asynchronously:
public class MySessionHandler extends StompSessionHandlerAdapter
{
@Override
public void afterConnected(StompSession session, StompHeaders connectedHeaders)
{
// WAITING FOR THIS
}
}
So question is: how the line WAITING HERE
should wait for the line WAITING FOR THIS
? Is there a specific Spring way of doing this? If not, which generic Java way fits here the best?
Maybe a java.util.concurrent.CountDownLatch
may solve your problem like this:
CountDownLatch latch = new CountDownLatch(1);
StompSessionHandler sessionHandler = new MySessionHandler(latch);
stompClient.connect("ws://server/endpoint", sessionHandler);
// wait here till latch will be zero
latch.await();
And your MySessionHandler
implementation:
public class MySessionHandler extends StompSessionHandlerAdapter {
private final CountDownLatch latch;
public MySessionHandler(final CountDownLatch latch) {
this.latch = latch;
}
@Override
public void afterConnected(StompSession session,
StompHeaders connectedHeaders) {
try {
// do here some job
} finally {
latch.countDown();
}
}
}
The solution with latch works. Later I discovered that connect
function returns ListenableFuture<StompSession>
, so we can wait for session to be created like this:
ListenableFuture<StompSession> future =
stompClient.connect("ws://server/endpoint", sessionHandler);
StompSession session = future.get(); // <--- this line will wait just like afterConnected()
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