带有SockJS连接的Spring Websocket丢失问题

时间:2019-03-16 07:09:24

标签: angular spring-boot spring-websocket sockjs

我正在使用spring boot,angular cli和sockjs开发一个Web应用程序。

WebSocket实现:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {

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

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/info", "/user", "/notif");
        registry.setApplicationDestinationPrefixes("/app");
    }
}

Angular websocket util实现:

注意:此类用于连接Web套接字和订阅例程!

@Injectable()
export class WebSocketUtil {

  stompClient = null;

  constructor() {
  }

  connect(subscribers: Subscriber[] = null) {
    let _this = this;
    let socket = new SockJS("https://localhost/ws");
    if (socket != null) {
      this.stompClient = Stomp.over(socket);
      if (this.stompClient != null) {
        console.log("Stomp client is connected!");

        let headers = {};
        headers["X-CSRF-TOKEN"] = ...;// csrf code

        this.stompClient.connect(headers, (frame) => {
          subscribers.forEach((subscriber) => {
            _this.stompClient.subscribe(subscriber.URL, subscriber.CALLBACK);
          });
        }, () => {
          console.log(_this.stompClient);
        });
      } else {
        throw {
          name: "StompClientNotRegistered",
          message: "Stomp client is not registered!"
        };
      }
    } else {
      throw {
        name: "SocketEstablishFailed",
        message: "Socket cannot be established!"
      };
    }
  }

  send(message) {
    this.stompClient.send(message.url, JSON.stringify(message.params));
  }
}

有角度的订户类实现:

注意:该类用于将订阅例程绑定到脚踩客户端!

export class Subscriber {
  constructor(private url: string = "", private callback: any) {
  }

  get URL() {
    return this.url;
  }

  get CALLBACK() {
    return this.callback;
  }
}

WebsocketUtil的用法:

注意:此代码段是在视图初始化阶段之后调用的。

this.webSocketUtil.connect([
      new Subscriber("/notif", function (data) {
        console.log(data);
      }),
      new Subscriber("/user", function (data) {
        console.log(data);
      })
    ]);

上面的代码在Web浏览器(FF和chrome)控制台中导致以下错误:

Browser error!

注意:https://localhost/ws可以访问,并返回“欢迎使用SockJS!”。消息。

1 个答案:

答案 0 :(得分:0)

最后,我解决了以下几点的问题:

  1. 向Apache2配置中添加适当的重写配置-我忽略了它:(

    public boolean coloringDone = false;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        mainActivity = this;
    
      ...
    
     tagListVU.setAdapter(adapter);
        tagListVU.deferNotifyDataSetChanged();
        tagListVU.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
    
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                tagListVU.removeOnLayoutChangeListener(this);
    
    
                   coloringDone = true;
    
            }
        });
    
  2. 向安全配置类中的 / ws 请求添加全部允许权限:

    @配置 @EnableWebSecurity 公共类WebSecurityConfig扩展了WebSecurityConfigurerAdapter {

    ...
    
    RewriteEngine On
    RewriteCond %{HTTP:Upgrade} =websocket [NC]
    RewriteRule ^/ws/(.*)       ws://localhost:8080/ws/$1 [P,L]    
    
    ...
    

    }

  3. 在websocket配置类中为SimpTypes添加允许所有权限:

    @配置 @EnableWebSocketMessageBroker 公共类WebSocketConfig扩展了AbstractSecurityWebSocketMessageBrokerConfigurer {     ...

    ...
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ...
        http.authorizeRequests().antMatchers("/ws/**").permitAll();
        ...
    }
    

    }