Delli Kilari
Delli Kilari

Reputation: 1016

Websocket with Spring mvc, stomp, sockjs, angular JS

With the example provided by spring.io and http://www.baeldung.com/websockets-spring is helped to create a websocket connection between client and server, but my case is. - Some one is creating message from UI that is passed to Spring controller (Separate controller). - From this controller I need to notify/send/broadcast this message to all connected clients. - How the message is passed to handler from controller where message is received. I also refereed WebSocket with Sockjs & Spring 4 but without Stomp here and the same question is posted.

Can some one help me here, Thanks in advance !!

Upvotes: 0

Views: 1439

Answers (1)

Adam Gerard
Adam Gerard

Reputation: 746

I actually write for Baeldung too and am currently writing a small article about how to add security to websockets in Spring! There are just a few steps you need to do to get this all working!

Backend-wise (since you said the UI was already done or being built, I'll just focus on the backend here), it really involves three parts: (1) the necessary POJO's, the controller, and the configuration.

Your POJO's will be very simple - here we just use Greeting and Message which specify a name and basic text data type (I'll skip over this here to save space but you can see it in the resource below).

Your controller will look like this:

@Controller
public class GreetingController {

    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Greeting greeting(HelloMessage message) throws Exception {
        Thread.sleep(1000); // simulated delay
        return new Greeting("Hello, " + message.getName() + "!");
    }

}

Take a look at the annotations - those are really what set this controller apart from say a normal REST controller.

And your configuration looks like this - again take a look at the annotations - particularly '@EnableWebSocketMessageBroker' - and the class 'AbstractWebSocketMessageBrokerConfigurer':

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/gs-guide-websocket").withSockJS();
    }
}

A look at this great resource too: https://spring.io/guides/gs/messaging-stomp-websocket/

Upvotes: 1

Related Questions