Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for Spring WebSocketStompClient to connect

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?

like image 983
ytrewq Avatar asked Dec 14 '22 04:12

ytrewq


2 Answers

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();
        }
    }
}
like image 144
vsminkov Avatar answered Dec 17 '22 01:12

vsminkov


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()
like image 29
ytrewq Avatar answered Dec 17 '22 02:12

ytrewq