Angular 7 + Java Spring - Websocket 返回 404

Angular 7 + Java Spring - Websocket returning 404

我正在尝试通过@stomp/stompjs 和 SockJS 库使用 Spring 4 Websocket 和 Angular 7,但是它一直返回 404 not found,并且与 websocket 的连接一直关闭结果。

我的配置代码在Spring:

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;

@Configuration
@EnableWebSocketMessageBroker
public class SocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/batch-socket").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/socketio/");
    }   
} 

SocketHandlerService.java发送消息模板

@Service
public class SocketHandlerService  extends AbsLogger<SocketHandlerService> implements ApplicationListener<BrokerAvailabilityEvent> {

   private final MessageSendingOperations<String> messagingTemplate;

   @Autowired
   public SocketHandlerService(MessageSendingOperations<String> messagingTemplate) {
       this.messagingTemplate = messagingTemplate;      
   }

   public SocketDetails sendRestMessage() {
         ...some code...
                        this.messagingTemplate.convertAndSend("/socketio/batchupdate", data);
         ...some code...            
     } 
   }

Angular socket.service.ts 在客户端处理 websockets

  init() {
    let connectionUrl = this.baseUrl + "batch-socket";

    return new Promise((resolve, reject) => {
        let config = new StompConfig();
        config.heartbeatOutgoing = 5000;
        config.heartbeatIncoming = 5000;
        config.webSocketFactory = function () {
          return new SockJS(connectionUrl, null, { transports: ['websocket' , 'xhr-streaming','xhr-polling' ] });
        }
        config.debug = function (str) {
          console.log("@socketDebug: " + str)
        }
      this.client = new Client();
      this.client.configure(config);

      enableLogs && console.log(this.client);
      console.log("@socketSvc: starting connection...");

      const _this = this;
      this.client.onConnect = function (frame) {
        console.log("@socketSvc: connection established.");
        console.log(frame);
        _this.state = new BehaviorSubject<any>(SocketClientState.ATTEMPTING);
        _this.state.next(SocketClientState.CONNECTED);
        resolve(frame.headers['user-name']);
      }

      this.client.onWebSocketClose = function (msg){
        console.log("@socketSvc: connection closed.");
        console.log(msg);
      }

      this.client.activate();
    });

  }

我已检查端点 URL 是否匹配,并且所使用的服务器和客户端的域也相同。但是,部署后会出现以下控制台输出:

POST https://exampleWebsite.com/Portal/batch-socket/718/ky4ln33y/xhr_send?t=1576031555275 404 (Not Found)
                                                           main.7459b10fe35bab2c58d4.js:179295 

@socketDebug: Connection closed to https://exampleWebsite.com/Portal/batch-socket 
                                                           main.7459b10fe35bab2c58d4.js:179310 

@socketSvc: connection closed.                             main.7459b10fe35bab2c58d4.js:179311 

i {type: "close", bubbles: false, cancelable: false, timeStamp: 1576031555344, wasClean: false, …}bubbles: falsecancelable: falsecode: 1006reason: "Sending error: Error: http status 404"timeStamp: 1576031555344type: "close" wasClean: false__proto__: r
                                                           main.7459b10fe35bab2c58d4.js:179295 

@socketDebug: STOMP: scheduling reconnection in 5000ms

我也看了浏览器的开发者工具来检查网络: network tab

请问连接关闭是什么问题?有时需要尝试几次才能成功建立 websocket。其他时候需要很长时间才能成功连接。

以下代码为我运行!!

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

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

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
         registry.addEndpoint("/batch-socket");
         registry.addEndpoint("/batch-socket").withSockJS();
    }
}

消息处理控制器:

@MessageMapping("/batch-socket")
@SendTo("/topic/messages")
public OutputMessage send(Message message) throws Exception {
    String time = new SimpleDateFormat("HH:mm").format(new Date());
    return new OutputMessage(message.getFrom(), message.getText(), time);
}

有效负载:

public class Message {

    private String from;
    private String text;

    // getters and setters
}