6

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.

1 Answer 1

7

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);
Sign up to request clarification or add additional context in comments.

2 Comments

I implemented your approach and now I get an exception 'Failed to start bean subProtocolWebSocketHandler'. I have created a post about it. Please take a look if you can. Thanks. stackoverflow.com/questions/37638396/…
hi, i have done the same process but my websocket is not called, i dont have any error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.