简体   繁体   中英

Stomp SockJs client + server Spring

I have a spring boot application, i use npm and webpack. I want to start a websocket to send some messages from server to client. My server is built with java, and the client with javascript using stomp and sockjs. Here's my code: Client:

    socket = new SockJS('/myWebSocketEndPoint');
    stompClient = Stomp.over(socket);
    stompClient.connect("","", function (frame) {
            console.log('Connected: ' + frame);
            stompClient.subscribe('/topic/notification', function (notificationBody) {
                  alert(angular.fromJson(notificationBody.body).content);
    });
  });
}

Server: Config:

    @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("/myWebSocketEndPoint").withSockJS();
    }
}

Controller:

    @SendTo("/topic/notification")
    public String sendToMenuItems(String menuItem)  {
          return menuItem;
    }

The problem is: when i want to run my application, it not makes upgrade with websocket (it seems that server is not working, or client not find server). So the upgrade request remains pending. If i use:

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/sockjs-client").withSockJS();
    }

and

    socket = new SockJS('/sockjs-client');

the upgrade works, but not connect and subscribe. Why if i use the second configuration my application (partially) works and if i use first configuration it doesn't? Thanks a lot

Try to replace:

stompClient.connect("","", function (frame) {
...

with:

stompClient.connect({}, function (frame) {
...

you don't have @MessageMapping("/sockjs-client") over the controller. try with this annotation along with @sendUser annotation.

I had to use setAllowedOriginPatterns to make this setup work

@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("/live");
        registry.addEndpoint("/live").setAllowedOriginPatterns("*").withSockJS();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM