从基本spring被动websocket服务器向非被动客户端发送消息

yhived7q  于 2021-07-14  发布在  Java
关注(0)|答案(0)|浏览(332)

问:如何将消息从spring被动websocket(服务器)发送到jswebsocket(客户端)?
我正在尝试将消息从标准spring被动websocket服务器发送到非被动js客户端。建立初始连接并将响应消息从服务器发送回客户端。但当我试图通过rest点调用custom方法向客户机发送消息时,消息并没有被发送。
流程是这样的,首先调用api rest端点来向处理程序发送消息给特定的客户机,然后客户机应该用restapi返回的响应进行响应。
查看了rsockets,但无法使用它们,因为我无法更改客户端,并且客户端只支持标准websockets。我还想知道使用被动服务器和客户端的轮询响应是否会提高性能,因为这看起来像是阻塞操作?
套接字处理程序:

  1. @Component
  2. public class ReactiveWebSocketHandler implements WebSocketHandler {
  3. Map<String, WebSocketSession> socketSessions = new HashMap<>();
  4. @Override
  5. public Mono<Void> handle(WebSocketSession session) {
  6. //Store current session in map.
  7. WebsocketContext.WEB_SOCKET_SESSIONS.put(session.getId(), session);
  8. Flux<WebSocketMessage> output = session.receive()
  9. .map(value -> session.textMessage("Subscription succesful, SessionId: " + session.getId()));
  10. return session.send(output);
  11. }
  12. public boolean sendMessageToClient(String sessionId) {
  13. //Get stored session and send message.
  14. WebSocketSession wss = WebsocketContext.WEB_SOCKET_SESSIONS.get(sessionId);
  15. var message = Mono.just(wss.textMessage("Server message"));
  16. wss.send(message);
  17. //for now true is returned but later this method should wait for answer from client in form of string
  18. return true;
  19. }
  20. }

存储套接字会话的上下文。

  1. public class WebsocketContext {
  2. public static Map<String, WebSocketSession> WEB_SOCKET_SESSIONS = new HashMap<>();
  3. }

配置:

  1. @Configuration
  2. public class WebConfig {
  3. @Bean
  4. public HandlerMapping webSocketHandlerMapping() {
  5. Map<String, WebSocketHandler> map = new HashMap<>();
  6. map.put("/websocket",new ReactiveWebSocketHandler());
  7. SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping();
  8. handlerMapping.setOrder(1);
  9. handlerMapping.setUrlMap(map);
  10. return handlerMapping;
  11. }
  12. @Bean
  13. public WebSocketHandlerAdapter handlerAdapter() {
  14. return new WebSocketHandlerAdapter();
  15. }
  16. }

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题