我正在尝试将自定义标头添加到客户端在第一次连接时收到的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连接之后由服务器发送的? –