我正在尝试在Angular和Spring Cloud之间建立WebSocket。它连接,但在创建后立即关闭连接,可能出错?
角度依赖:
"sockjs-client": "^1.1.4",
"stompjs": "^2.3.3",
Spring WebSocket配置:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry
.addEndpoint("/gs-guide-websocket")
.withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
// prefix for subscribe
config.enableSimpleBroker("/topic");
// prefix for send
config.setApplicationDestinationPrefixes("/app");
}
}
和CORSFilter合作起源:
public class CORSFilter implements Filter {
// This is to be replaced with a list of domains allowed to access the server
//You can include more than one origin here
private final List<String> allowedOrigins = Arrays.asList("http://localhost:3000");
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
// Lets make sure that we are working with HTTP (that is, against HttpServletRequest and HttpServletResponse objects)
if (req instanceof HttpServletRequest && res instanceof HttpServletResponse) {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
// Access-Control-Allow-Origin
String origin = request.getHeader("Origin");
response.setHeader("Access-Control-Allow-Origin", allowedOrigins.contains(origin) ? origin : "");
response.setHeader("Access-Control-Allow-Credentials", "true");
}
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {
}
}
添加到http:
http.addFilterBefore(new CORSFilter(), SessionManagementFilter.class)
;
角度代码:
Stomp.over(new SockJS('http://localhost:8080/gs-guide-websocket')).connect({}, () => {
console.log('TEST');
}, () => {
console.log('FAILS');
});
和Stacktrace:
stomp.js:134 Opening Web Socket...
core.es5.js:2925 Angular is running in the development mode. Call enableProdMode() to enable the production mode.
stomp.js:134 Web Socket Opened...
stomp.js:134 >>> CONNECT
accept-version:1.1,1.0
heart-beat:10000,10000
stomp.js:134 Whoops! Lost connection to http://localhost:8080/gs-guide-websocket
app.component.ts:50 FAILS
由于