2017-02-10 1 views
0

첫 번째 연결에서 클라이언트가받은 STOMP 'CREATED'메시지에 사용자 지정 헤더를 추가하려고합니다. 하여 브라우저의 콘솔에 다음과 같은
Spring Boot 애플리케이션의 STOMP CREATED 메시지에 맞춤 헤더를 추가하는 방법은 무엇입니까?

function connect() { 
    socket = new SockJS('/chat'); 
    stompClient = Stomp.over(socket); 
    stompClient.connect('', '', function(frame) { 
     whoami = frame.headers['user-name']; 
     console.log(frame); 
     stompClient.subscribe('/user/queue/messages', function(message) { 
      console.log("MESSAGE RECEIVED:"); 
      console.log(message); 

     showMessage(JSON.parse(message.body)); 
     }); 
     stompClient.subscribe('/topic/active', function(activeMembers) { 
     showActive(activeMembers); 
     }); 
    }); 
    } 

이 기능은 인쇄합니다 : 여기 STOMP 자바 스크립트를 사용하여 웹 소켓에 연결하는 기능입니다

body: "" 
command: "CONNECTED" 
headers: Object 
    heart-beat: "0,0" 
    user-name: "someuser" 
    version: "1.1" 

그리고 난 출력이 같이 있어야하므로 사용자 정의 헤더를 추가 할 :

body: "" 
command: "CONNECTED" 
headers: Object 
    heart-beat: "0,0" 
    user-name: "someuser" 
    version: "1.1" 
    custom-header: "foo" 

스프링 부트 응용 프로그램에 다음과 같은 WebSocket 구성이 있습니다.

WebSocketConfig.java는

@Configuration 
@EnableWebSocketMessageBroker 
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { 

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

    @Override 
    public void registerStompEndpoints(StompEndpointRegistry registry) { 
    registry.addEndpoint("/chat", "/activeUsers") 
      .withSockJS() 
      .setInterceptors(customHttpSessionHandshakeInterceptor()); 
    } 

    ... 

    @Bean 
    public CustomHttpSessionHandshakeInterceptor 
     customHttpSessionHandshakeInterceptor() { 
     return new CustomHttpSessionHandshakeInterceptor(); 

    } 

} 

나는 사용자 정의 헤더를 설정하는 'HandshakeInterceptor'을 등록하는 것을 시도했다, 그러나 그것은 작동하지 않았다. 나는이 방법이 작동하지 않는 이유 누군가가 나를 설명 할 수 https://dzone.com/articles/spring-boot-based-websocket
에서이 코드를 발견

public class CustomHttpSessionHandshakeInterceptor implements 

HandshakeInterceptor { 

    @Override 
     public boolean beforeHandshake(ServerHttpRequest request, 
     ServerHttpResponse response, 
     WebSocketHandler wsHandler, 
     Map<String, Object> attributes) throws Exception { 
      if (request instanceof ServletServerHttpRequest) { 


       ServletServerHttpRequest servletRequest = 
        (ServletServerHttpRequest) request; 
       attributes.put("custom-header", "foo"); 
      } 
      return true; 
     } 

     public void afterHandshake(ServerHttpRequest request, 
      ServerHttpResponse response, 
      WebSocketHandler wsHandler, 
      Exception ex) { } 
} 



CustomHttpSessionHandshakeInterceptor.java : 여기 CustomHttpSessionHandshakeInterceptor '는 무엇입니까? Spring Boot 애플리케이션의 서버 측에서 STOMP 'CREATED'메시지에 커스텀 헤더를 설정하는 또 다른 방법이 있습니까?
감사합니다.

답변

0

이렇게하면 좋았습니까? MessageHeaderAccessor에는 setHeader 메소드도 있습니다. https://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html#websocket-stomp-authentication-token-based

+0

예, 나는 'MessageHeaderAccessor'를 사용하는 시도하고 봄의 '@MessageMapping'주석 방법에 의해 처리되고에서 'SimpMessagingTemplate'에서 보낸 일반 메시지 STOMP 'MESSAGE'명령 메시지 (위해 완벽하게 작동 내 경우). 질문은 WebSocket 연결을 설정 한 후 서버에서 보낸 STOMP 'CONNECTED'명령을 사용하여 메시지에 사용자 지정 헤더를 추가하는 방법입니다. –

0

은 어쩌면 너무 늦었어요,하지만 결코보다 늦게 ... (예를 들어 연결됨)

서버 메시지는 불변,이 수정 될 수 있음을 의미한다.

클라이언트 아웃 바운드 인터셉터를 등록하고 preSend (...) 메소드를 재정 의하여 연결 메시지를 트랩하고 사용자 정의 헤더로 새 메시지를 작성합니다.

@Override 
    public Message<?> preSend(Message<?> message, MessageChannel channel) { 

     LOGGER.info("Outbound channel pre send ..."); 

     final StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(message); 
     final StompCommand command = headerAccessor.getCommand(); 

     if (!isNull(command)) { 

      switch (command) { 

      case CONNECTED: 
final StompHeaderAccessor accessor = StompHeaderAccessor.create(headerAccessor.getCommand()); 
       accessor.setSessionId(headerAccessor.getSessionId()); 
     @SuppressWarnings("unchecked") 
     final MultiValueMap<String, String> nativeHeaders = (MultiValueMap<String, String>) headerAccessor.getHeader(StompHeaderAccessor.NATIVE_HEADERS); 
     accessor.addNativeHeaders(nativeHeaders); 

// add custom headers 
accessor.addNativeHeader("CUSTOM01", "CUSTOM01"); 

     final Message<?> newMessage = MessageBuilder.createMessage(new byte[0], accessor.getMessageHeaders()); 
       return newMessage; 
      default: 
       break; 
      } 
     } 

     return message; 
    } 
관련 문제