每当有新的连接时,角Springwebsocket总是关闭连接

8ehkhllq  于 2021-07-26  发布在  Java
关注(0)|答案(0)|浏览(260)

我试图通过Angular9和代理的express服务器连接到SpringWebSocket服务器。但每次我连接到websocket服务器时,它总是断开连接。当我直接通过“ng-serve”(不是通过express代理服务器)运行时,没有出现这个问题。这是我的代码
代理服务器:

var backendEndPoint = process.env.URECON_BACKEND_END_POINT || 'http://localhost:9000';
var frontendPort = process.env.URECON_FRONTEND_PORT || 4200; //default port of node server or angular CLI server
var websocketEndPoint = backendEndPoint.replace('http', 'ws');

var express = require('express');
var httpProxy = require('http-proxy');
var path = require('path');

// create server
var app = express();
var proxy = httpProxy.createProxyServer();

// proxy for websocket
app.all('/api/ws', function (req, res) {
     console.log('Websocket forward!');
     proxy.web(req, res, { target: 'ws://localhost:9000', ws: true, secure: false });
});

// // proxy HTTP GET / POST
// app.all('/auth/signin', function (req, res) {
//      proxy.web(req, res, { target: backendEndPoint });
// });
app.all('/api/*', function (req, res) {
     proxy.web(req, res, { target: backendEndPoint });
});

// // Proxy websockets
// app.on('upgrade', function (req, socket, head) {
//      console.log("proxying upgrade request", req.url);
//      proxy.ws(req, socket, head);
// });

//built in middleware to serve static content just as images, css, html etc
app.use(express.static(path.resolve(__dirname, 'dist/recon-angular')));

app.listen(frontendPort, () => {
     console.log('uRecon Frontend App Running on port:', frontendPort);
     console.log('uRecon Backend Endpoint:', backendEndPoint);
     console.log('uRecon Backend Websocket Endpoint:', websocketEndPoint);
});

我的客户:

this.stompClient = Stomp.over(websocket);
      // this.stompClient.debug = () => { };
      console.log('Trying to connect via websocket!');
      this.stompClient.connect(
        {
          Authorization: 'Bearer ' + this.storgeService.get(StorageService.TOKEN_KEY)
        }, // header
        () => {// onConnect
          this.stompClient.send('/app/registerReportConfigSocket', {},
            JSON.stringify(id));
        }, (error) => {
          console.log('Fail to connect ws manually', error);
        });

websocket配置:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic", "/queue");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/api/ws").setAllowedOrigins("*");
        registry.addEndpoint("/api/ws").setAllowedOrigins("*").withSockJS();
    }

    @Override
    public void configureWebSocketTransport(WebSocketTransportRegistration registry) {
        registry.setMessageSizeLimit(800 * 1024);
        registry.setSendBufferSizeLimit(1024 * 1024);
        registry.setSendTimeLimit(20000);
        WebSocketMessageBrokerConfigurer.super.configureWebSocketTransport(registry);
    }

}

websocket列表编号:

@EventListener
    public void handleWebSocketConnectListener(SessionConnectedEvent event) {
        log.info("One connection opened! Session Id = " + event.getMessage().getHeaders().get("simpSessionId"));
    }

    @EventListener
    public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
        log.info("One connection closed! Session Id = " + event.getMessage().getHeaders().get("simpSessionId"));
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
        algoResultServices.releaseLockRootCause(event.getUser().getName(), event.getSessionId());

        Integer activeLearningThreadId = (Integer) headerAccessor.getSessionAttributes().get("threadId");
        if(activeLearningThreadId != null) activeLearningService.removeActiveTask(activeLearningThreadId);

        Integer reportId = (Integer) headerAccessor.getSessionAttributes().get("reportId");
        if(reportId != null) reportConfigService.unlockReportConfig(reportId);

    }

spring安全配置:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors()
            .configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues())
            .and()
            .csrf().disable()
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .authorizeRequests()
            .antMatchers("/auth/signin").permitAll()
            .antMatchers("/ws/**").permitAll();
            .anyRequest().authenticated();
        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    }

断开连接时的错误代码:

请帮我解决这个问题!非常感谢你们

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题