spring-guides / gs-messaging-stomp-websocket

Using WebSocket to build an interactive web application :: Learn how to the send and receive messages between a browser and the server over a WebSocket
http://spring.io/guides/gs/messaging-stomp-websocket/
Apache License 2.0
530 stars 474 forks source link

Not able to configure Stomp and SockJS endpoint in Spring MVC.Connection issue !!! #42

Closed ShantaramTupe closed 6 years ago

ShantaramTupe commented 6 years ago

I am implementing Notification System. And want to initialize Socket connection when user Logged In, and show him his notifications, and also if some event happens.

My Code snippet as follows.

websocket.js :

var stompClient = null;
function connect( temp ) {
    alert(temp);
    //var socket = new SockJS("/websock");
    //var socket = new SockJS("/websock"+temp);
    var socket = new SockJS(context_path+"/websock"+temp);
    //context_path == "/SupportCenter"
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function( frame ){
        console.log( "Connected :- "+frame );
        stompClient.subscribe("/topic/notifications", function( notifications ) {
            alert( notifications );
        });
    }, function( error ) {
        alert( error );
    });
    alert();
    getNotifications();
}

function getNotifications() {
    stompClient.send("/app/hello", {}, "Hiiiiii");
}

WebSocketConfig.java :

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
        stompEndpointRegistry.addEndpoint("/websock").withSockJS();
    }
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        // TODO Auto-generated method stub
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }
}

WebSocketController.java :

@Controller
public class WebSocketController {

    @MessageMapping(value="/hello")
    @SendTo("/topic/notifications")
    public Notify hello() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Notify notify = new Notify();
        notify.setMessage("Hello World !!!");
        return notify;
    }
}

Some code Hom.jsp :

<script type="text/javascript" src="<c:url value="/resources/js/sockjs.min.js"/>"></script>
<script type="text/javascript" src="<c:url value="/resources/js/stomp.min.js"/>"></script>
<script type="text/javascript" src="<c:url value="/resources/js/websocket.js"/>"></script>

<script type="text/javascript">
$(document).ready(function() {
    //...

    connect( '${nsec}');
});

Why Firefox Console giving XML Parsing Error: no root element found Location: while in Network tab status code is 200 OK. ? What is the cause for this, any suggestions?

Versions I'm using Spring-MVC - 4.1.6 STOMP - 1.7.1 SockJS-client - 1.1.4

Console TAB
websocket_connection_error6

Network TAB
websocket_connection_error5

ShantaramTupe commented 6 years ago

solved this by

function connect( temp ) {
    alert(temp);
    //var socket = new SockJS("/websock");
    //var socket = new SockJS("/websock"+temp);
    var socket = new SockJS(context_path+"/websock"+temp);
    //context_path == "/SupportCenter"
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function( frame ){
        console.log( "Connected :- "+frame );
        stompClient.subscribe("/topic/notifications", function( notifications ) {
            alert( notifications );
        });
    getNotifications();//************Changed Here
    }, function( error ) {
        alert( error );
    });
}
arthurlima96 commented 6 years ago

Would like to look at how settings in your project, could you make your repository available? I am using a project with the same versions, please

ShantaramTupe commented 6 years ago

@arthurlima96 Project is quite big, not able to make it available as repository, what issue you are facing ?

arthurlima96 commented 6 years ago

I'm facing configuration issues like: pom.xml (from websocket without Spring Boot) and where to add the WebSocketConfig configuration class

It´s my error https://gist.github.com/anonymous/09e526be8c9acb469f2302b2051db4ea

` public class ServletSpringMVC extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getRootConfigClasses() {
    return new Class<?>[] {AppWebConfiguration.class};
}

@Override
protected Class<?>[] getServletConfigClasses() {
    return new Class<?>[]{WebSocketConfig.class};
}

@Override
protected String[] getServletMappings() {
    return new String[] {"/"};
}

@Override
protected void customizeRegistration(Dynamic registration) {
    registration.setAsyncSupported(true);
}

} `

` @Configuration @EnableWebSocketMessageBroker

@ComponentScan(basePackageClasses={SockController.class}) public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
    System.out.println("WEB 1");
    config.enableSimpleBroker("/topic");
    config.setApplicationDestinationPrefixes("/app");
}

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
    System.out.println("WEB 2");
    registry.addEndpoint("/chat").setAllowedOrigins("*").withSockJS();
}

} `

rstoyanchev commented 6 years ago

You've java.lang.NoSuchMethodError coming from WebSocketMessageBrokerConfigurationSupport which is trying to call CustomScopeConfigurer.addScope. That method was added in 4.1.1 so it looks like you have a pre-4.1.1 spring-beans on your classpath. Use mvn dependency:tree to analyze what's pulling it in.

Keep in mind 4.3.x is the only currently supported branch for the 4th generation, and the only one that continues to get fixes (including security fixes). So you need to be on the latest 4.3.x.

arthurlima96 commented 6 years ago

I solved the spring-bean version, thank you very much @rstoyanchev .

Sonia-dev commented 3 years ago

Invalid SockJS path '/topic/public' - required to have 3 path segments same error !!!