Java 无法运行 spring web socket演示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21877373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Not able to run spring web socket demo
提问by Harry Joy
I am trying to run a demo of spring web socket but not able to test it completely. I am using java 7 and tomcat 7.0.50. I don't get any error while server startup, but when I open the web page with js making the connection to it I got 404 page not found. I am not sure if I am missing anything in configuration to make it run and how can I be able to connect it from js side.
我正在尝试运行 spring web socket 的演示,但无法完全测试它。我正在使用 java 7 和 tomcat 7.0.50。服务器启动时我没有收到任何错误,但是当我使用 js 打开网页时,我找不到 404 页面。我不确定我是否缺少配置中的任何内容以使其运行,以及如何从 js 端连接它。
I have following xml file:
我有以下xml文件:
<beans ....>
<context:annotation-config />
<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>
My controller class is:
我的控制器类是:
@Controller
public class SwsService {
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
return new Greeting("Hello, " + message.getName() + "!");
}
public String getGreeting() {
return "Hello, you are in!";
}
}
The js from which I am calling this is:
我调用它的 js 是:
var sock = new SockJS("/hello");
sock.onopen = function () {
console.log("open");
};
sock.onclose = function () {
console.log("closed");
};
sock.onmessage = function (message) {
console.log("msg", message);
};
The console output when I run the tomcat:
运行tomcat时的控制台输出:
Feb 19, 2014 3:28:47 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre7\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jre6/bin/client;C:/Program Files/Java/jre6/bin;C:/Program Files/Java/jre6/lib/i386;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Intel\OpenCL SDK.0\bin\x86;C:\Program Files\TortoiseGit\bin;C:\Python24;C:\Program Files\TortoiseSVN\bin;C:\Program Files\nodejs\;C:\Program Files\Git\cmd;C:\Users\harsh\AppData\Roaming\npm;E:\IDE\eclipse_indigo;;.
Feb 19, 2014 3:28:47 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:SWS' did not find a matching property.
Feb 19, 2014 3:28:48 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Feb 19, 2014 3:28:48 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Feb 19, 2014 3:28:48 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1412 ms
Feb 19, 2014 3:28:48 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Feb 19, 2014 3:28:48 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.50
Feb 19, 2014 3:28:51 PM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
Feb 19, 2014 3:28:51 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
Feb 19, 2014 3:28:51 PM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization started
Feb 19, 2014 3:28:51 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing Root WebApplicationContext: startup date [Wed Feb 19 15:28:51 IST 2014]; root of context hierarchy
Feb 19, 2014 3:28:52 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/classes/conf/SwsContext.xml]
Feb 19, 2014 3:28:53 PM org.springframework.scheduling.concurrent.ExecutorConfigurationSupport initialize
INFO: Initializing ExecutorService 'clientInboundChannelExecutor'
Feb 19, 2014 3:28:53 PM org.springframework.scheduling.concurrent.ExecutorConfigurationSupport initialize
INFO: Initializing ExecutorService 'clientOutboundChannelExecutor'
Feb 19, 2014 3:28:53 PM org.springframework.scheduling.concurrent.ExecutorConfigurationSupport initialize
INFO: Initializing ExecutorService 'messageBrokerSockJsScheduler'
Feb 19, 2014 3:28:53 PM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/hello/**] onto handler of type [class org.springframework.web.socket.sockjs.support.SockJsHttpRequestHandler]
Feb 19, 2014 3:28:53 PM org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup start
INFO: Starting beans in phase 2147483647
Feb 19, 2014 3:28:53 PM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization completed in 2173 ms
Feb 19, 2014 3:28:53 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Feb 19, 2014 3:28:53 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Feb 19, 2014 3:28:53 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 5842 ms
The browser console output:
浏览器控制台输出:
GET http://localhost:8080/hello/info 404 (Not Found) sockjs-0.3.min.js:27
closed
How can I successfully test it?
我怎样才能成功测试它?
Updates
更新
I also tried running the portfolio example from here: https://github.com/rstoyanchev/spring-websocket-portfolioas suggested by @jhadesdev
我还尝试从这里运行投资组合示例:https: //github.com/rstoyanchev/spring-websocket-portfolio按照@jhadesdev 的建议
But it also doesn't help. When I run mvn tomcat7:run
, I see following output and open url on browser tells 404.
但这也无济于事。当我运行时mvn tomcat7:run
,我看到以下输出并在浏览器上打开 url 告诉 404。
[INFO] Scanning for projects...
[INFO]
[INFO] Using the builder org.apache.maven.lifecycle.internal.builder.singlethrea
ded.SingleThreadedBuilder with a thread count of 1
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building spring-websocket-portfolio 1.0.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] >>> tomcat7-maven-plugin:2.2:run (default-cli) @ spring-websocket-portfol
io >>>
[INFO]
[INFO] --- maven-resources-plugin:2.5:resources (default-resources) @ spring-web
socket-portfolio ---
[debug] execute contextualize
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory E:\libraries\spring-websocket-portfol
io\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ spring-websoc
ket-portfolio ---
[INFO] No sources to compile
[INFO]
[INFO] <<< tomcat7-maven-plugin:2.2:run (default-cli) @ spring-websocket-portfol
io <<<
[INFO]
[INFO] --- tomcat7-maven-plugin:2.2:run (default-cli) @ spring-websocket-portfol
io ---
[INFO] Running war on http://localhost:8080/spring-websocket-portfolio
[INFO] Using existing Tomcat server configuration at E:\libraries\spring-websock
et-portfolio\target\tomcat
[INFO] create webapp with contextPath: /spring-websocket-portfolio
Feb 27, 2014 10:20:46 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Feb 27, 2014 10:20:46 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Tomcat
Feb 27, 2014 10:20:46 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.47
Feb 27, 2014 10:20:49 AM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
Feb 27, 2014 10:20:49 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
It stuck there and doesn't go ahead.
它卡在那里,没有继续前进。
回答by Roadrunner
ThisChrome extension can help you test Websockets.
这个Chrome 扩展可以帮助你测试 Websockets。
Also you can have a look at my simple-chatproject that uses Spring Bootwith Websockets.
你也可以看看我的简单聊天项目,它使用带有 Websockets 的Spring Boot。
回答by Angular University
Try adding an assets folder inside webapp, where all the stomp and sockjs.js files are made available. Have a look at this example of a running application, that can be run with mvn clean install jetty:run
.
尝试在 webapp 中添加一个 assets 文件夹,其中所有 stomp 和 sockjs.js 文件都可用。看看这个正在运行的应用程序的例子,它可以用mvn clean install jetty:run
.
The problem seems to be that either the sockjs is not on the server or some path is wrong. Based on the example on the link, a stomp endpoint can be configured like this:
问题似乎是 sockjs 不在服务器上或某些路径错误。根据链接上的示例,可以像这样配置stomp 端点:
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/portfolio").withSockJS();
}
}
Then in javascript the end point can be called like this:
然后在 javascript 中,终点可以这样调用:
var socket = new SockJS('/spring-websocket-portfolio/portfolio')
var stompClient = Stomp.over(socket);
where /spring-websocket-portfolio
is the root deployment path of your application.
/spring-websocket-portfolio
应用程序的根部署路径在哪里。
回答by Brian Clozel
Your application looks fine.
您的应用程序看起来不错。
You should definitely prefix JavaScript requests with the root context of your application, as jhadesdev mentioned.
正如jhadesdev 提到的,您绝对应该使用应用程序的根上下文作为 JavaScript 请求的前缀。
Does your application registers additional filters or customize messageconverters? Maybe some other element of configuration is interfering here.
您的应用程序是否注册了额外的过滤器或自定义消息转换器?也许其他一些配置元素在这里干扰。
The latest portfolio example should definitely work, here are some questions:
最新的投资组合示例绝对有效,这里有一些问题:
- Could you tell us more about your client setup (browser, version)?
- Does your browser support websocket (test it there)?
- Could you also try in incognito mode (maybe a 3rd party browser extension is at fault here)?
- Could you check that your browser is not using a HTTP proxy for localhost requests?
- Could you check if this HTTP 404 is in Tomcat access log? (and see if you've got something interesting in those or in catalina.out?)
- 您能告诉我们更多有关您的客户端设置(浏览器、版本)的信息吗?
- 您的浏览器是否支持 websocket(在那里测试)?
- 您是否也可以尝试使用隐身模式(可能是第 3 方浏览器扩展程序有问题)?
- 您能检查一下您的浏览器是否没有对 localhost 请求使用 HTTP 代理吗?
- 你能检查一下这个 HTTP 404 是否在 Tomcat 访问日志中吗?(看看你是否在那些或 catalina.out 中有一些有趣的东西?)
回答by user3901192
I was facing the same problem. This thread gave me enough clues to solve the problem. Thanks a lot.
我面临同样的问题。这个线程给了我足够的线索来解决这个问题。非常感谢。
SOLUTION:In case you have a Spring MVC Dispatcher Servlet configured in your web.xml and mapped to a url-pattern as shown below
解决方案:如果您在 web.xml 中配置了 Spring MVC Dispatcher Servlet 并映射到如下所示的 url-pattern
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/webui/*</url-pattern>
</servlet-mapping>
Then you have to create the SockJS instance as shown below
然后你必须创建 SockJS 实例,如下所示
var socket = new SockJS('/contextPath/webui/hello');
NOTE:Replace contextPathwith your application context path.
注意:将contextPath替换为您的应用程序上下文路径。
回答by dawidklos
回答by tn2000
I solved this problem in thats way: when you create the SockJS add localhost:8080/ like this
我以这种方式解决了这个问题:当你创建 SockJS 时,像这样添加 localhost:8080/
new SockJS('http://localhost:8080/spring-websocket-portfolio/portfolio')
回答by Bogdan Kobylynskyi
For me the solution was to enable SockJS
in by WebSocketConfig
class:
对我来说,解决方案是SockJS
按WebSocketConfig
类启用:
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/search")
.setAllowedOrigins("*")
.setHandshakeHandler(new DefaultHandshakeHandler())
.withSockJS();
}