Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 238
James Avatar asked Jun 24 '14 18:06

James


1 Answers

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);
like image 146
Evgeni Dimitrov Avatar answered Sep 19 '22 12:09

Evgeni Dimitrov