Search code examples
spring-mvcwebsocketspring-websocket

spring-mvc, websockets push integration


I've followed this link http://spring.io/guides/gs/messaging-stomp-websocket/ and got the app up and running.

What I wanted was a little more than that, I wanted to to be able to push the data back to the client without the client having to send any thing.

So I've setup a long running task with a listener similar to the below

GreetingController implements RunnableListener and the RunnableListener has a method public Greeting greeting(HelloMessage message);

The implementation of the method is to kick off a thread and then call the listener method..

I see the output on the console when that happens, but I don't see anything on the browser.

Could anyone please show me how to kick off a running task and let the server push the content to the browser using Spring instead of poll (setTimeout stuff in javascript?)

Regards Tin


Solution

  • What is this RunnableListener interface? What is triggering this task - is it scheduled regularly?

    Once the client has subscribed to a given topic (here, /topic/greetings), you can send messages to that topic whenever you want using a MessagingTemplate. For example, you could schedule this task and let it send messages regularly on a given topic:

    @Service
    public class GreetingService {
    
        private SimpMessagingTemplate template;
    
        @Autowired
        public GreetingService(SimpMessagingTemplate template) {
            this.template = template;
        }
    
        @Scheduled(fixedDelay=10000)
        public void greet() {
            this.template.convertAndSend("/topic/greetings", "Hello");
        }
    
    }
    

    Check out the reference documentation for more details.