java - Spring 4 WebSocket 应用程序

标签 java spring jsp spring-mvc websocket

我尝试从 spring 站点运行这个示例:tutorial 除了 Spring Boot 部分。

Web.xml

<web-app>
    <display-name>Archetype Created Web Application</display-name>

    <servlet>
        <servlet-name>sample</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextClass</param-name>
            <param-value>
                org.springframework.web.context.support.AnnotationConfigWebApplicationContext
            </param-value>
        </init-param>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                com.evgeni.websock.WebSocketConfig
            </param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>sample</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

Java 配置:

@Configuration
@ComponentScan(basePackages = {"com.evgeni.controller"})
@EnableWebSocketMessageBroker
@EnableWebMvc
public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketMessageBrokerConfigurer  {

    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/hello").withSockJS();
    }

    public void configureClientInboundChannel(ChannelRegistration registration) {
        // TODO Auto-generated method stub

    }

    public void configureClientOutboundChannel(ChannelRegistration registration) {
        // TODO Auto-generated method stub

    }

    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic");
        registry.setApplicationDestinationPrefixes("/app"); 
    }
     @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/css/**").addResourceLocations("/css/").setCachePeriod(31556926);
            registry.addResourceHandler("/img/**").addResourceLocations("/img/").setCachePeriod(31556926);
            registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(31556926);
        }

}

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() + "!");
    }

}

索引.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
    <title>Hello WebSocket</title>
    <script src="<c:url value='/js/sockjs-0.3.js'/>"></script>
    <script src="<c:url value='/js/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>

除了我从 web.xml 加载的 conf 和 jsp 中的 2-3 c:url 以添加项目的根目录外,一切都与教程相同。

当我点击连接然后发送时,在浏览器控制台中我得到:

Opening Web Socket... stomp.js:122
Web Socket Opened... stomp.js:122
>>> CONNECT
login:
passcode:
accept-version:1.1,1.0
heart-beat:10000,10000

 stomp.js:122
<<< ERROR
message:Illegal header\c 'login\c'. A header must be of the form <name>\c<value>
content-length:0

 stomp.js:122
>>> SEND
destination:/websock/app/hello
content-length:14

{"name":"asd"} 

我认为问题出在Sock js的connect函数上

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

我正在传递 '' 作为登录名和密码。

编辑: 当我将连接函数更改为 stompClient.connect('random', 'random', 时,控制台中的响应是:

Opening Web Socket... stomp.js:122
Web Socket Opened... stomp.js:122
>>> CONNECT
login:asd
passcode:asd
accept-version:1.1,1.0
heart-beat:10000,10000

 stomp.js:122
<<< CONNECTED
heart-beat:0,0
version:1.1

 stomp.js:122
connected to server undefined stomp.js:122
Connected: CONNECTED
version:1.1
heart-beat:0,0

 (index):23
>>> SUBSCRIBE
id:sub-0
destination:/websock/topic/greetings

 stomp.js:122
>>> SEND
destination:/websock/app/hello
content-length:14

{"name":"asd"} 

但是消息没有传递给 Controller ​​。

最佳答案

错误是错误的 Controller 映射。 我有:

  @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Greeting greeting(HelloMessage message) throws Exception

在 jsp 中:

stompClient.subscribe("<c:url value='/topic/greetings'/>", function(greeting){...

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

正确的是:

stompClient.subscribe('/topic/greetings', function(greeting){...
stompClient.send('/app/hello', {}, JSON.stringify({ 'name': name }));

c:url 添加了项目的根,当我删除它时,应用程序可以正常工作。但是,在此处使用 SockJs 创建新套接字时需要 c:url(根目录):

var socket = new SockJS("<c:url value='/hello'/>");

关于java - Spring 4 WebSocket 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20740956/

相关文章:

java - 访问二维数组时出现 NullPointerException

java - OpenGL ES - 主线程上的工作太多

java - 如何制作自定义对象副本? java

java - 如何增加从java数据库中获取特定值的时间?

spring - jar 的 META-INF 文件夹中的 pom.xml 的目的是什么?

spring - 增加 Grails/Tomcat 事件 HTTP 连接限制

java - 检查 JSTL 中的对象是否是新的

java - 如何将对象从jsp发送到servlet

java - com.fasterxml.jackson.databind.JsonMappingException : Multiple back-reference properties with name 'defaultReference'

javascript - 使用 JSP 编辑已加载的 HTML 文本的最佳方法是什么?