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.

James
  • 1,720
  • 5
  • 29
  • 50

1 Answers1

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);
riddle_me_this
  • 8,575
  • 10
  • 55
  • 80
Evgeni Dimitrov
  • 21,976
  • 33
  • 120
  • 145
  • 1
    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. http://stackoverflow.com/questions/37638396/getting-a-failed-to-start-bean-subprotocolwebsockethandler-exception-while-try – An Illusion Jun 05 '16 at 05:57
  • hi, i have done the same process but my websocket is not called, i dont have any error. – Afroz Shaikh Aug 12 '16 at 07:42