gpt4 book ai didi

java - 如何使用 Spring 实现自定义 WebSocket 子协议(protocol)

转载 作者:行者123 更新时间:2023-11-30 06:04:55 25 4
gpt4 key购买 nike

我必须在 Spring Boot 应用程序中添加对自定义 WebSocket 子协议(protocol)(因此不是 STOMP)的支持,但我很难理解我需要提供什么以及 Spring 已经拥有什么。

这就是我走了多远:

@Configuration
@EnableWebSocket
public class WebSocketAutoConfiguration implements WebSocketConfigurer {

public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
webSocketHandlerRegistry.addHandler(this.webSocketHandler(), new String[]{endpointUrl});
}

@Bean
public WebSocketHandler webSocketHandler() {
ExecutorSubscribableChannel clientInboundChannel = new ExecutorSubscribableChannel();
ExecutorSubscribableChannel clientOutboundChannel = new ExecutorSubscribableChannel();
SubProtocolWebSocketHandler subProtocolWebSocketHandler = new SubProtocolWebSocketHandler(clientInboundChannel, clientOutboundChannel);
subProtocolWebSocketHandler.addProtocolHandler(new SubProtocolHandler() {
public List<String> getSupportedProtocols() {
return Collections.singletonList("custom-protocol");
}

public void handleMessageFromClient(WebSocketSession session, WebSocketMessage<?> message, MessageChannel outputChannel) throws Exception {
session.sendMessage(new TextMessage("some message"));
}

public void handleMessageToClient(WebSocketSession session, Message<?> message) throws Exception {
}

public String resolveSessionId(Message<?> message) {
return UUID.randomUUID().toString();
}

public void afterSessionStarted(WebSocketSession session, MessageChannel outputChannel) throws Exception {
System.out.println("SESSION STARTED");
}

public void afterSessionEnded(WebSocketSession session, CloseStatus closeStatus, MessageChannel outputChannel) throws Exception {
session.close();
System.out.println("SESSION ENDED");
}
});
return subProtocolWebSocketHandler;
}
}

从某种意义上说,这是可行的,handleMessageFromClient确实在网络套接字消息上触发,但我无法理解MessageChannel outputChannelhandleMessageToClient<的目的.

是否可以使用 SubProtocolWebSocketHandler 获取 PerConnectionWebSocketHandler 语义?

与此相关的文档基本上不存在,例如handleMessageToClient 的文档说:

Handle the given {@link Message} to the client associated with the given WebSocket session.

嗯,太棒了。而且 STOMP 实现令人难以置信,因此它们作为指南不太有用。

任何例子,广泛的步骤或任何东西,真的,将不胜感激。

最佳答案

事实证明这非常简单。根本不需要搞乱 SubProtocolWebSocketHandler 。唯一的要求是提供的 WebSocketHandler 实现 SubProtocolCapable

public class CustomHandler implements WebSocketHandler, SubProtocolCapable {
...
}

仅此而已。要创建 PerConnectionWebSocketHandler,只需扩展它并实现 SubProtocolCapable 就足够了:

public class CustomHandler extends PerConnectionWebSocketHandler implements SubProtocolCapable {
...
}

关于java - 如何使用 Spring 实现自定义 WebSocket 子协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51528992/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com