Kiril S. Kiril S. - 3 months ago 67
Java Question

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?

Answer

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();
        }
    }
}