Angular 7 + Java Spring-Websocket返回404

问题描述 投票:0回答:1

[我试图通过@ stomp / stompjs和SockJS库使用Spring 4 Websocket和Angular 7,但是它始终返回404,并且与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...            
     } 
   }

用于在客户端处理websocket的Angular socket.service.ts

  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。其他时间,永远需要成功的连接。

angular spring websocket stomp sockjs
1个回答
0
投票

以下代码为我运行!

@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
}
© www.soinside.com 2019 - 2024. All rights reserved.