Spring 4 Websocket - Nothing happens

2020-07-22 17:49发布

问题:

I am learning spring 4 websocket and i will be much thankful if anyone can guide me to learn spring 4 websocket step by step or can suggest some book where i can find step by step practical approach on the said subject.

But before that a little help needed here with this snippet that i am trying to execute on eclipse using tomcat 8 .

index.html

<!DOCTYPE html>
<html>
<head>
<title>Hello WebSocket</title>
<script src="https://raw.githubusercontent.com/spring-guides/gs-messaging-stomp-websocket/master/complete/src/main/resources/static/sockjs-0.3.4.js"></script>
<script src="https://raw.githubusercontent.com/spring-guides/gs-messaging-stomp-websocket/master/complete/src/main/resources/static/stomp.js"></script>
<script type="text/javascript">
    var stompClient = null;

    function setConnected(connected) {
        document.getElementById('connect').disabled = connected;
        document.getElementById('disconnect').disabled = !connected;
        document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
        document.getElementById('response').innerHTML = '';
    }

    function connect() {
        var socket = new SockJS("<c:url value='/hello'/>");
        stompClient = Stomp.over(socket);
        stompClient.connect('', '', function(frame) {
            setConnected(true);
            console.log('Connected: ' + frame);
            stompClient.subscribe("<c:url value='/topic/greetings'/>", function(greeting){
                showGreeting(JSON.parse(greeting.body).content);
            });
        });
    }

    function disconnect() {
        stompClient.disconnect();
        setConnected(false);
        console.log("Disconnected");
    }

    function sendName() {
        var name = document.getElementById('name').value;
        stompClient.send("<c:url value='/app/hello'/>", {}, JSON.stringify({ 'name': name }));
    }

    function showGreeting(message) {
        var response = document.getElementById('response');
        var p = document.createElement('p');
        p.style.wordWrap = 'break-word';
        p.appendChild(document.createTextNode(message));
        response.appendChild(p);
    }
</script>
</head>
<body>
<noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websocket relies on Javascript being enabled. Please enable
Javascript and reload this page!</h2></noscript>
<div>
<div>
    <button id="connect" onclick="connect();">Connect</button>
    <button id="disconnect" disabled="disabled" onclick="disconnect();">Disconnect</button>
</div>
<div id="conversationDiv">
    <label>What is your name?</label><input type="text" id="name" />
    <button id="sendName" onclick="sendName();">Send</button>
    <p id="response"></p>
</div>
</div>
</body>
</html>

Greeting.java

public class Greeting {

private String content;

public Greeting(String content) {
    this.content = content;
}

public String getContent() {
    return content;
}

}

GreetingController.java

import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;

@Controller
public class GreetingController {

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

}

HelloMessage.java

package com.iiw.controller.relationship;

public class HelloMessage {

private String name;

public String getName() {
    return name;
}

}

WebsocketConfig.xml

<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>

web.xml

    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="WebApp_ID"
         version="3.0">
  <display-name>CRUDWebAppMavenized</display-name>

   <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>

   <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml , /WEB-INF/SecurityContext.xml , /WEB-INF/WebSocketConfig.xml</param-value>

</context-param>

   <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>

  <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>classpath:log4j.xml</param-value>
    </context-param>

    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

  <welcome-file-list>

    <welcome-file>index.jsp</welcome-file>

  </welcome-file-list>
</web-app>

The Problem is everytime i am running this code, this is giving nothing

回答1:

Change connect function

from:

function connect() {
        var socket = new SockJS("<c:url value='/hello'/>");
        stompClient = Stomp.over(socket);
        stompClient.connect('', '', function(frame) {
            setConnected(true);
            console.log('Connected: ' + frame);
            stompClient.subscribe("<c:url value='/topic/greetings'/>", function(greeting){
                showGreeting(JSON.parse(greeting.body).content);
            });
        });
    }

To:

function connect() {
        var socket = new SockJS("<c:url value='/hello'/>");
        stompClient = Stomp.over(socket);
        stompClient.connect('', '', function(frame) {
            setConnected(true);
            console.log('Connected: ' + frame);
            stompClient.subscribe('/topic/greetings', function(greeting){
                showGreeting(JSON.parse(greeting.body).content);
            });
        });
    }

and similarly for sendName()

From:

function sendName() {
        var name = document.getElementById('name').value;
        stompClient.send("<c:url value='/app/hello'/>", {}, JSON.stringify({ 'name': name }));
    }

To:

function sendName() {
        var name = document.getElementById('name').value;
        stompClient.send('/app/hello', {}, JSON.stringify({ 'name': name }));
    }