问:如何将消息从spring被动websocket(服务器)发送到jswebsocket(客户端)?
我正在尝试将消息从标准spring被动websocket服务器发送到非被动js客户端。建立初始连接并将响应消息从服务器发送回客户端。但当我试图通过rest点调用custom方法向客户机发送消息时,消息并没有被发送。
流程是这样的,首先调用api rest端点来向处理程序发送消息给特定的客户机,然后客户机应该用restapi返回的响应进行响应。
查看了rsockets,但无法使用它们,因为我无法更改客户端,并且客户端只支持标准websockets。我还想知道使用被动服务器和客户端的轮询响应是否会提高性能,因为这看起来像是阻塞操作?
套接字处理程序:
@Component
public class ReactiveWebSocketHandler implements WebSocketHandler {
Map<String, WebSocketSession> socketSessions = new HashMap<>();
@Override
public Mono<Void> handle(WebSocketSession session) {
//Store current session in map.
WebsocketContext.WEB_SOCKET_SESSIONS.put(session.getId(), session);
Flux<WebSocketMessage> output = session.receive()
.map(value -> session.textMessage("Subscription succesful, SessionId: " + session.getId()));
return session.send(output);
}
public boolean sendMessageToClient(String sessionId) {
//Get stored session and send message.
WebSocketSession wss = WebsocketContext.WEB_SOCKET_SESSIONS.get(sessionId);
var message = Mono.just(wss.textMessage("Server message"));
wss.send(message);
//for now true is returned but later this method should wait for answer from client in form of string
return true;
}
}
存储套接字会话的上下文。
public class WebsocketContext {
public static Map<String, WebSocketSession> WEB_SOCKET_SESSIONS = new HashMap<>();
}
配置:
@Configuration
public class WebConfig {
@Bean
public HandlerMapping webSocketHandlerMapping() {
Map<String, WebSocketHandler> map = new HashMap<>();
map.put("/websocket",new ReactiveWebSocketHandler());
SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping();
handlerMapping.setOrder(1);
handlerMapping.setUrlMap(map);
return handlerMapping;
}
@Bean
public WebSocketHandlerAdapter handlerAdapter() {
return new WebSocketHandlerAdapter();
}
}
暂无答案!
目前还没有任何答案,快来回答吧!