问题描述
在使用spring的方式集成websocket时,在配置WebSocketConfigurer后
@Configuration
@EnableWebSocket
public class WebSocketConfiguration implements WebSocketConfigurer {@ResourceServletWebSocketServerHandler servletWebSocketServerHandler;@Overridepublic void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {// 配置处理器registry.addHandler(servletWebSocketServerHandler, "/")// 配置拦截器.addInterceptors(new ServletWebSocketHandshakeInterceptor())// 解决跨域问题.setAllowedOrigins("*");}
}
ServerEndpoint代码
@Component
@ServerEndpoint(value = "/websocket/{key}")
public class MqWebSocketServer extends AbstractWebSocketServer {@Overridepublic void onOpen(Session session, String key) {}@Overridepublic void onMessage(String message, Session session, String key) {}@Overridepublic void onClose(Session session, String key) {}@Overridepublic void onError(Session session, Throwable throwable) {}
}
用postman请求发现结果时 404 ,错误信息如下
Could not connect to ws://127.0.0.1:9095/spring-boot-websocket/websocket/123
10:04:52
Error: Unexpected server response: 404
Handshake Details
Request URL: http://127.0.0.1:9095/spring-boot-websocket/websocket/123
Request Method: GET
Status Code: 404
错误原因
请求地址应为ws://127.0.0.1:9095/spring-boot-websocket,因为在实现WebSocketConfigurer后配置的路径为全路径,不是匹配路径