我正在学习使用Spring WebSockets,但我不能得到一个非常基本的例子来工作,我收到一个404错误。我使用http://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html作为参考。
WebSocketConfig:
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
private Logger logger = Logger.getLogger(WebSocketConfig.class);
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
logger.debug("Registering websocket handler");
registry.addHandler(gameWebSocketHandler(), "/StreamGame/ws/play");
}
@Bean
public WebSocketHandler gameWebSocketHandler() {
return new GameWebSocketHandler();
}
}
WebSocketHandler:
public class GameWebSocketHandler extends TextWebSocketHandler {
final static Logger logger = Logger.getLogger(GameWebSocketHandler.class);
public GameWebSocketHandler() {
logger.debug("Constructor handler");
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
super.handleTransportError(session, exception);
logger.error("Transport error: " + exception.getMessage());
}
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
logger.info("Handle message received: " + message.getPayload());
//session.sendMessage(new TextMessage("Here is your answer"));
}
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
super.afterConnectionEstablished(session);
logger.info("Connection established!");
}
}
除非我错了,即使这样,我也应该能够通过websocket从客户端发送消息到服务器,如下所示:
sock = new WebSocket('ws://localhost:8080/StreamGame/ws/play');
我收到以下错误连接:
WebSocket握手错误:Unexpected response code: 404WrappedWebSocket @ VM84:35(匿名函数)@ (index):11j @ jquery-3.1.1.min.js:2k @ jquery-3.1.1.min.js:2(index):26 Error undefined
Web.xml包含以下内容:
<!-- Processes application requests -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/application-context.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>SpringMVCDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/application-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Mapping websocket to spring dispatcher servlet -->
<servlet-mapping>
<servlet-name>SpringMVCDispatcherServlet</servlet-name>
<url-pattern>/ws/*</url-pattern>
</servlet-mapping>
我的Spring应用程序上下文包含:
当连接websocket时,我在服务器日志中看到以下内容:
> 2016-11-13 TRACE - 39804 - org.springframework.web.servlet.DispatcherServlet -
> http-nio-8080-exec-2 - Bound request context to thread:
> org.apache.catalina.connector.RequestFacade@df5f117
> 2016-11-13 DEBUG - 39804 - org.springframework.web.servlet.DispatcherServlet -
> http-nio-8080-exec-2 - DispatcherServlet with name
> 'SpringMVCDispatcherServlet' processing GET request for
> [/StreamGame/ws/play]
> 2016-11-13 TRACE - 39804 - org.springframework.web.servlet.DispatcherServlet -
> http-nio-8080-exec-2 - Testing handler map
> [org.springframework.web.socket.server.support.WebSocketHandlerMapping@4e92ebf3]
> in DispatcherServlet with name 'SpringMVCDispatcherServlet'
> 2016-11-13 TRACE - 39804 - org.springframework.web.socket.server.support.WebSocketHandlerMapping
> - http-nio-8080-exec-2 - No handler mapping found for [/play]
> 2016-11-13 WARN - 39804 - org.springframework.web.servlet.PageNotFound - http-nio-8080-exec-2 -
> No mapping found for HTTP request with URI [/StreamGame/ws/play] in
> DispatcherServlet with name 'SpringMVCDispatcherServlet'
似乎你的websocket url是不正确的。您注册了/play作为处理程序,但是调用了/StreamGame/play
还要记住,ws连接是异步创建的,因此在发送消息之前必须等待连接握手完成,如下所示:
var ws = new WebSocket("ws://localhost:8080/play");
ws.onopen = function() {
ws.send('AHOIHOI');
}
ws.onerror = function(error) {
// handle connection error
}
addHandler函数需要映射到'/play',因此排除根上下文(StreamGame)和调度程序映射(/ws)。更改addHandler解决了这个问题:
registry.addHandler(gameWebSocketHandler(), "/play");
websocket打开时连接如下:
sock = new WebSocket('ws://localhost:8080/StreamGame/ws/play');