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.
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);
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