websocket_sockJS : 全部传输错误。添加 { transports: ['websocket']} 后

websocket_sockJS : all transport error. after adding { transports: ['websocket']}

背景:

每当我打开 WebSocket 页面时 我有几个XHR_SEND? 404 - 错误但最终 XHR_SEND?获得成功响应并连接到 WebSocket。

所以为了避免这个 404 错误,我决定只使用 WebSocket。所以我添加了这个

: return new SockJS(connectionUrl, null, { 传输: ['websocket']});

然后现在.. XHR_SEND?都不见了,但它根本没有连接到服务器。

+仅供参考:我有 2 个服务器 ..(我想因为这个我以前得到 XHR_send 错误。)

下面的截图是重复的。但从未连接

JAVA

@Configuration
@EnableWebSocketMessageBroker
public class BatchSocketConfiguration extends AbstractWebSocketMessageBrokerConfigurer {



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



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



    }

角度 7

import { Injectable, OnDestroy, Inject, Optional } from '@angular/core';
import * as SockJS from '../../../assets/lib/sockjs.min.js';
import { BehaviorSubject, Observable } from 'rxjs';
import { filter, first, switchMap } from 'rxjs/operators';
import { StompSubscription, Stomp, Client, Frame, Message, StompConfig, Versions } from '@stomp/stompjs';


@Injectable({
  providedIn: 'root'
})
export class SocketService {

  private client: Client;
  private state: BehaviorSubject<any>;
  private baseUrl: any = "/" + window.location.href.substr(0).split('/')[3] + "/";

  constructor() {
  }

  init() {
    let connectionUrl = this.baseUrl + "batch-socket";
    console.log("MY URL is " + connectionUrl);
    return new Promise((resolve, reject) => {
        let config = new StompConfig();
        config.heartbeatOutgoing = 10000;
        config.heartbeatIncoming = 10000;
        config.stompVersions = new Versions(['1.0', '1.1']);
        config.webSocketFactory = function () {
          return new SockJS(connectionUrl, null, { transports: ['websocket']});
          //PREVIOUS : return new SockJS(connectionUrl)
        }
        config.debug = function (str) {
          console.log("@socketDebug: " + str)
        }
      this.client = new Client();
      this.client.configure(config);

      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.onWebSocketError = function(msg){
        console.log("@socketSvc: connection error.");
        console.log(msg);
      }

      this.client.onDisconnect = function(msg){
        console.log("@socketSvc: socket disconnected.");
        console.log(msg);
        //this.init();
      }

      this.client.onStompError = function(msg){
        console.log("@socketSvc: stomp error occurred.");
        console.log(msg);
      }

      this.client.activate();
    });

  }

  private connect(): Observable<Client> {
    return new Observable<Client>(observer => {
      this.state.pipe(filter(state => state === SocketClientState.CONNECTED)).subscribe(() => {
        observer.next(this.client);
      });
    });
  }

  onPlainMessageReceived(topic: string): Observable<string> {
    return this.onMessageReceived(topic, SocketService.textHandler);
  }

  onMessageReceived(topic: string, handler = SocketService.jsonHandler): Observable<any> {
    return this.connect().pipe(first(), switchMap(client => {
      return new Observable<any>(observer => {
        const subscription: StompSubscription = client.subscribe(topic, message => {
          observer.next(handler(message));
        });
        return () => client.unsubscribe(subscription.id);
      });
    }));
  }

  static jsonHandler(message: Message): any {
    return JSON.parse(message.body);
  }

  static textHandler(message: Message): string {
    return message.body;
  }


  disconnect() {
    this.connect().pipe(first()).subscribe(client => client.deactivate());
    this.client.deactivate();
  }
}

export enum SocketClientState {
  ATTEMPTING, CONNECTED
}

我找到了这个问题的原因。 我意识到我有 2 war 个文件。 因此一个有我的代码(套接字连接),另一个没有代码(套接字连接)。 所以它抛出错误。

=> 通过删除没有套接字连接的 war 文件解决。