哎呀!与未定义的连接丢失 - 连接建立后连接丢失 [英] Whoops! Lost connection to undefined - Connection Lost Just After The Connection Established

查看:36
本文介绍了哎呀!与未定义的连接丢失 - 连接建立后连接丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近几天我一直在尝试 spring 4 websocket.但有个问题我使用的是 apache-tomcat-8,这不是一个 Maven 项目.

这是我的片段

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %><%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><头><title>Hello WebSocket</title><script type="text/javascript" src="./js/sockjs-0.3.4.js"></script><script type="text/javascript" src="./js/stomp.js"></script><script type="text/javascript">var stompClient = null;功能集连接(连接){document.getElementById('connect').disabled = connected;document.getElementById('disconnect').disabled = !connected;document.getElementById('conversationDiv').style.visibility = connected ?'可见':'隐藏';document.getElementById('response').innerHTML = '';}函数连接(){var socket = new SockJS("<c:url value='/hello'/>");stompClient = Stomp.over(socket);stompClient.connect({}, function(frame) {设置连接(真);console.log('已连接:' + 框架);window.alert('已连接:' + 框架);stompClient.subscribe('/topic/greetings', function(greeting){showGreeting(JSON.parse(greeting.body).content);});});}函数断开(){如果(stompClient != null){stompClient.disconnect();}设置连接(假);console.log("断开连接");}函数发送名称(){var name = document.getElementById('name').value;stompClient.send("/app/hello", {}, JSON.stringify({ 'name': name }));}功能 showGreeting(message) {var response = document.getElementById('response');var p = document.createElement('p');p.style.wordWrap = '断字';p.appendChild(document.createTextNode(message));response.appendChild(p);}<身体><noscript><h2 style="color: #ff0000">您的浏览器似乎不支持 Javascript!Websocket 依赖于启用的 Javascript.请启用Javascript 并重新加载此页面!</h2></noscript><div><div><button id="connect" onclick='connect();'>Connect</button><button id="disconnect" disabled="disabled" onclick="disconnect();">Disconnect</button>

<div id="conversationDiv"><label>你叫什么名字?</label><input type="text" id="name"/><button id="sendName" onclick="sendName();">发送</button><p id="响应"></p>

</html>

WebSocketConfig.xml

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:websocket="http://www.springframework.org/schema/websocket"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/websockethttp://www.springframework.org/schema/websocket/spring-websocket.xsd"><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></豆类>

HelloMessage.java

package com.springws.test;公共类 HelloMessage {私人字符串名称;公共字符串 getName() {返回名称;}}

Greeting.java

package com.springws.test;公开课问候{私有字符串内容;公共问候(字符串内容){this.content = 内容;}公共字符串 getContent() {返回内容;}}

GreetingController.java

package com.springws.test;导入 org.springframework.messaging.handler.annotation.MessageMapping;导入 org.springframework.messaging.handler.annotation.SendTo;导入 org.springframework.stereotype.Controller;@控制器公共类问候控制器{@MessageMapping("/你好")@SendTo("/topic/greetings")公共问候问候(HelloMessage 消息)抛出异常 {System.out.println(message.getName());return new Greeting("Hello, " + message.getName() + "!");}}

web.xml

<display-name>CRUDWebAppMavenized</display-name><监听器><监听器类>org.springframework.web.context.ContextLoaderListener</listener-class></监听器><上下文参数><param-name>contextConfigLocation</param-name><参数值>/WEB-INF/WebSocketConfig.xml</context-param><小服务程序><servlet-name>spring</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><启动时加载>1</启动时加载><servlet-mapping><servlet-name>spring</servlet-name><url-pattern>/</url-pattern></servlet-mapping><欢迎文件列表><welcome-file>index.jsp</welcome-file></welcome-file-list></web-app>

spring-servlet.xml

WebSocketConfig.java

package com.springws.test;导入 org.springframework.context.annotation.ComponentScan;导入 org.springframework.context.annotation.Configuration;导入 org.springframework.messaging.simp.config.MessageBrokerRegistry;导入 org.springframework.stereotype.Controller;导入 org.springframework.web.servlet.config.annotation.EnableWebMvc;导入 org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;导入 org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;导入 org.springframework.web.socket.config.annotation.StompEndpointRegistry;@配置@ComponentScan(basePackages = {"com.springws.test"})@EnableWebSocketMessageBroker@EnableWebMvc@控制器公共类 WebSocketConfig 扩展 AbstractWebSocketMessageBrokerConfigurer {@覆盖公共无效 configureMessageBroker(MessageBrokerRegistry 配置){config.enableSimpleBroker("/topic");config.setApplicationDestinationPrefixes("/app");}@覆盖public void registerStompEndpoints(StompEndpointRegistry registry) {registry.addEndpoint("/hello").withSockJS();}}

图书馆

但是在浏览器控制台中

它给出以下输出

正在打开 Web 套接字...stomp.js:145 Web 套接字已打开...stomp.js:145 >>>连接接受版本:1.1,1.0心跳:10000,10000哎呀!与未定义的连接丢失

为什么会失去连接?

解决方案

我找到了答案.我错过了三个图书馆.

<块引用>

  1. jackson-annotations-2.5.1.jar ,
  2. jackson-core-2.5.1.jar ,
  3. jackson-databind-2.5.1.jar

我删除了旧库 jackson-annotations-2.1.2.jar 并添加了这三个库.现在它的工作就像一个 deram

For Last couple of days i have been trying spring 4 websocket . But There is a problem I am using apache-tomcat-8 and this is not a maven project.

Here are my snippets

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Hello WebSocket</title>
    <script type="text/javascript" src="./js/sockjs-0.3.4.js"></script>
    <script type="text/javascript" src="./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);
                window.alert('Connected: ' + frame);
                stompClient.subscribe('/topic/greetings', function(greeting){
                    showGreeting(JSON.parse(greeting.body).content);
                });
            });
        }

        function disconnect() {
            if (stompClient != null) {
                stompClient.disconnect();
            }
            setConnected(false);
            console.log("Disconnected");
        }

        function sendName() {
            var name = document.getElementById('name').value;
            stompClient.send("/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>

WebSocketConfig.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:websocket="http://www.springframework.org/schema/websocket"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/websocket
        http://www.springframework.org/schema/websocket/spring-websocket.xsd">

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

</beans>

HelloMessage.java

package com.springws.test;

public class HelloMessage {

    private String name;

    public String getName() {
        return name;
    }

}

Greeting.java

package com.springws.test;

public class Greeting {

    private String content;

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

    public String getContent() {
        return content;
    }

}

GreetingController.java

package com.springws.test;

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 {

        System.out.println(message.getName());
        return new Greeting("Hello, " + message.getName() + "!");
    }

}

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/WebSocketConfig.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>


  <welcome-file-list>

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

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

spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
            http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/context   http://www.springframework.org/schema/context/spring-context-3.0.xsd
            http://www.springframework.org/schema/jee       http://www.springframework.org/schema/jee/spring-jee.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
            http://www.springframework.org/schema/aop       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <mvc:annotation-driven/>
    <mvc:default-servlet-handler/>

    <context:annotation-config />

    <context:component-scan base-package="com.springws.test" /> 

    <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <tx:annotation-driven />

</beans>

WebSocketConfig.java

package com.springws.test;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;

@Configuration
@ComponentScan(basePackages = {"com.springws.test"})
@EnableWebSocketMessageBroker
@EnableWebMvc
@Controller
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("/hello").withSockJS();
    }


}

Libraries

But in browser console

its giving the following output

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

Whoops! Lost connection to undefined

why its losing connection ?

解决方案

I Found the Answer. I missed three libraries.

  1. jackson-annotations-2.5.1.jar ,
  2. jackson-core-2.5.1.jar ,
  3. jackson-databind-2.5.1.jar

and i removed the old library jackson-annotations-2.1.2.jar and added these three libraries . And Now its workig like a deram

这篇关于哎呀!与未定义的连接丢失 - 连接建立后连接丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆