websocket_sockJS:所有传输错误。添加{传输后:['websocket']}

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

背景:

无论何时打开WebSocket页面我有几个XHR_SEND? 404-错误,但最终还是XHR_SEND?得到成功响应并连接到WebSocket。

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

:返回新的SockJS(connectionUrl,null,{传输:['websocket']});

那么现在..XHR_SEND?不见了,但根本没有连接到服务器。

+ FYI:我有2台服务器..(我想因为这个原因,我之前收到XHR_send错误。)

下面的屏幕截图正在重复。但从未连接

enter image description here

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/");



    }

ANGULAR7

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
}
websocket angular7 sockjs
1个回答
0
投票

我找到了此问题的原因。我意识到我有2个战争档案。因此,一个有我的代码(套接字连接),另一个没有我的代码(套接字连接)。因此会引发错误。

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

© www.soinside.com 2019 - 2024. All rights reserved.