我正在嘗試將自定義標頭添加到客戶端在第一次連接時收到的STOMP'CREATED'消息。這裏是連接到使用STOMP JavaScript的WebSocket的功能:
如何在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);
});
});
}
此功能打印以下瀏覽器的控制檯:
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"
我在我的Spring Boot應用程序中有以下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' 設置自定義標題,但沒有奏效。這裏是 'CustomHttpSessionHandshakeInterceptor':
CustomHttpSessionHandshakeInterceptor.java
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) { }
}
我發現在https://dzone.com/articles/spring-boot-based-websocket
這個代碼片斷有人可以解釋我爲什麼這個方法行不通?在Spring Boot應用程序中,是否有另一種方法將自定義標頭設置爲服務器端的STOMP'CREATED'消息?
謝謝!
是的,我試圖用「MessageHeaderAccessor」,它完全適用於它們通過Spring的「@MessageMapping」註解的方法進行處理,並通過「SimpMessagingTemplate」在發送與STOMP「消息」的命令消息(普通郵件我的情況)。問題是,如何在STOMP'CONNECTED'命令中爲消息添加自定義標頭,這是在建立WebSocket連接之後由服務器發送的? –