James
James

Reputation: 1780

Push message from Java with Spring 4 WebSocket

I'd like to push messages from Java to WebSocket clients. I've successfully made a js client send to the server and receive a message back on 2 js clients, so the client side code works fine.

My issue is that I'd like to initiate a send when events occur within the Java app. So for example every time 10 orders have been placed send a message to all subscribed clients. Is this possible?

My current config:

<websocket:message-broker application-destination-prefix="/app">
   <websocket:stomp-endpoint path="/hello">
        <websocket:sockjs/>
   </websocket:stomp-endpoint>
   <websocket:simple-broker prefix="/topic"/>
</websocket:message-broker>

@Controller
public class MessageController {
    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Greeting greeting() throws Exception {
       return new Greeting("Hello world");
    }
}

What I'd like to be able to do is something like this:

public class OrderManager {
    @Autowired MessageController messageController;
    int orderCount = 0;

    public void processOrder(Order o) {
        orderCount++;
        if(orderCount % 10 == 0)
            messageController.greeting();
    }
}

and all subscribed clients to the websocket receive a message.

Upvotes: 6

Views: 5264

Answers (1)

Evgeni Dimitrov
Evgeni Dimitrov

Reputation: 22496

You can use the SimpMessagingTemplate. It's automatically registered. Just autowire it in any Spring bean you want.

@Autowired
private SimpMessagingTemplate template;
...
this.template.convertAndSend("/topic/greetings", text);

Upvotes: 7

Related Questions