Search in sources :

Example 1 with WebSocketHandler

use of org.springframework.web.reactive.socket.WebSocketHandler in project spring-framework by spring-projects.

the class RxNettyWebSocketClient method executeInternal.

@SuppressWarnings("cast")
private Observable<Void> executeInternal(URI url, HttpHeaders headers, WebSocketHandler handler) {
    String[] protocols = beforeHandshake(url, headers, handler);
    return createRequest(url, headers, protocols).flatMap(response -> {
        Observable<WebSocketConnection> conn = response.getWebSocketConnection();
        return (Observable<Tuple2<WebSocketResponse<ByteBuf>, WebSocketConnection>>) Observable.zip(Observable.just(response), conn, Tuples::of);
    }).flatMap(tuple -> {
        WebSocketResponse<ByteBuf> response = tuple.getT1();
        WebSocketConnection conn = tuple.getT2();
        HandshakeInfo info = afterHandshake(url, toHttpHeaders(response));
        ByteBufAllocator allocator = response.unsafeNettyChannel().alloc();
        NettyDataBufferFactory factory = new NettyDataBufferFactory(allocator);
        RxNettyWebSocketSession session = new RxNettyWebSocketSession(conn, info, factory);
        session.aggregateFrames(response.unsafeNettyChannel(), WsClientDecoder.getName());
        return RxReactiveStreams.toObservable(handler.handle(session));
    });
}
Also used : NettyDataBufferFactory(org.springframework.core.io.buffer.NettyDataBufferFactory) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) Tuples(reactor.util.function.Tuples) Tuple2(reactor.util.function.Tuple2) HashMap(java.util.HashMap) Function(java.util.function.Function) ArrayList(java.util.ArrayList) Observable(rx.Observable) ByteBuf(io.netty.buffer.ByteBuf) Map(java.util.Map) HttpClient(io.reactivex.netty.protocol.http.client.HttpClient) WebSocketHandler(org.springframework.web.reactive.socket.WebSocketHandler) URI(java.net.URI) HttpClientRequest(io.reactivex.netty.protocol.http.client.HttpClientRequest) RxEventLoopProvider(io.reactivex.netty.threads.RxEventLoopProvider) WebSocketResponse(io.reactivex.netty.protocol.http.ws.client.WebSocketResponse) HandshakeInfo(org.springframework.web.reactive.socket.HandshakeInfo) HttpHeaders(org.springframework.http.HttpHeaders) ObjectUtils(org.springframework.util.ObjectUtils) RxNettyWebSocketSession(org.springframework.web.reactive.socket.adapter.RxNettyWebSocketSession) WebSocketConnection(io.reactivex.netty.protocol.http.ws.WebSocketConnection) Mono(reactor.core.publisher.Mono) WebSocketRequest(io.reactivex.netty.protocol.http.ws.client.WebSocketRequest) List(java.util.List) RxReactiveStreams(rx.RxReactiveStreams) WsClientDecoder(io.reactivex.netty.protocol.http.HttpHandlerNames.WsClientDecoder) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) WebSocketConnection(io.reactivex.netty.protocol.http.ws.WebSocketConnection) RxNettyWebSocketSession(org.springframework.web.reactive.socket.adapter.RxNettyWebSocketSession) ByteBuf(io.netty.buffer.ByteBuf) NettyDataBufferFactory(org.springframework.core.io.buffer.NettyDataBufferFactory) Observable(rx.Observable) Tuple2(reactor.util.function.Tuple2) Tuples(reactor.util.function.Tuples) HandshakeInfo(org.springframework.web.reactive.socket.HandshakeInfo)

Example 2 with WebSocketHandler

use of org.springframework.web.reactive.socket.WebSocketHandler in project tutorials by eugenp.

the class ReactiveWebSocketConfiguration method webSocketHandlerMapping.

@Bean
public HandlerMapping webSocketHandlerMapping() {
    Map<String, WebSocketHandler> map = new HashMap<>();
    map.put("/event-emitter", webSocketHandler);
    SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping();
    handlerMapping.setOrder(1);
    handlerMapping.setUrlMap(map);
    return handlerMapping;
}
Also used : HashMap(java.util.HashMap) WebSocketHandler(org.springframework.web.reactive.socket.WebSocketHandler) SimpleUrlHandlerMapping(org.springframework.web.reactive.handler.SimpleUrlHandlerMapping) Bean(org.springframework.context.annotation.Bean)

Example 3 with WebSocketHandler

use of org.springframework.web.reactive.socket.WebSocketHandler in project spring-cloud-gateway by spring-cloud.

the class WebSocketIntegrationTests method subProtocol.

@Test
public void subProtocol() throws Exception {
    String protocol = "echo-v1";
    String protocol2 = "echo-v2";
    AtomicReference<HandshakeInfo> infoRef = new AtomicReference<>();
    MonoProcessor<Object> output = MonoProcessor.create();
    client.execute(getUrl("/sub-protocol"), new WebSocketHandler() {

        @Override
        public List<String> getSubProtocols() {
            return Arrays.asList(protocol, protocol2);
        }

        @Override
        public Mono<Void> handle(WebSocketSession session) {
            infoRef.set(session.getHandshakeInfo());
            return session.receive().map(WebSocketMessage::getPayloadAsText).subscribeWith(output).then();
        }
    }).block(Duration.ofMillis(5000));
    HandshakeInfo info = infoRef.get();
    assertThat(info.getHeaders().getFirst("Upgrade")).isEqualToIgnoringCase("websocket");
    assertThat(info.getHeaders().getFirst("Sec-WebSocket-Protocol")).isEqualTo(protocol);
    assertThat(info.getSubProtocol()).as("Wrong protocol accepted").isEqualTo(protocol);
    assertThat(output.block(Duration.ofSeconds(5))).as("Wrong protocol detected on the server side").isEqualTo(protocol);
}
Also used : WebSocketHandler(org.springframework.web.reactive.socket.WebSocketHandler) AtomicReference(java.util.concurrent.atomic.AtomicReference) WebSocketMessage(org.springframework.web.reactive.socket.WebSocketMessage) HandshakeInfo(org.springframework.web.reactive.socket.HandshakeInfo) WebSocketSession(org.springframework.web.reactive.socket.WebSocketSession) Test(org.junit.Test)

Example 4 with WebSocketHandler

use of org.springframework.web.reactive.socket.WebSocketHandler in project spring-framework by spring-projects.

the class ReactorNettyRequestUpgradeStrategy method upgrade.

@Override
public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler, @Nullable String subProtocol, Supplier<HandshakeInfo> handshakeInfoFactory) {
    ServerHttpResponse response = exchange.getResponse();
    HttpServerResponse reactorResponse = ServerHttpResponseDecorator.getNativeResponse(response);
    HandshakeInfo handshakeInfo = handshakeInfoFactory.get();
    NettyDataBufferFactory bufferFactory = (NettyDataBufferFactory) response.bufferFactory();
    URI uri = exchange.getRequest().getURI();
    // Trigger WebFlux preCommit actions and upgrade
    return response.setComplete().then(Mono.defer(() -> {
        WebsocketServerSpec spec = buildSpec(subProtocol);
        return reactorResponse.sendWebsocket((in, out) -> {
            ReactorNettyWebSocketSession session = new ReactorNettyWebSocketSession(in, out, handshakeInfo, bufferFactory, spec.maxFramePayloadLength());
            return handler.handle(session).checkpoint(uri + " [ReactorNettyRequestUpgradeStrategy]");
        }, spec);
    }));
}
Also used : HttpServerResponse(reactor.netty.http.server.HttpServerResponse) NettyDataBufferFactory(org.springframework.core.io.buffer.NettyDataBufferFactory) ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse) HandshakeInfo(org.springframework.web.reactive.socket.HandshakeInfo) RequestUpgradeStrategy(org.springframework.web.reactive.socket.server.RequestUpgradeStrategy) Mono(reactor.core.publisher.Mono) ReactorNettyWebSocketSession(org.springframework.web.reactive.socket.adapter.ReactorNettyWebSocketSession) Supplier(java.util.function.Supplier) WebsocketServerSpec(reactor.netty.http.server.WebsocketServerSpec) ServerWebExchange(org.springframework.web.server.ServerWebExchange) ServerHttpResponseDecorator(org.springframework.http.server.reactive.ServerHttpResponseDecorator) Nullable(org.springframework.lang.Nullable) WebSocketHandler(org.springframework.web.reactive.socket.WebSocketHandler) URI(java.net.URI) Assert(org.springframework.util.Assert) HttpServerResponse(reactor.netty.http.server.HttpServerResponse) WebsocketServerSpec(reactor.netty.http.server.WebsocketServerSpec) ReactorNettyWebSocketSession(org.springframework.web.reactive.socket.adapter.ReactorNettyWebSocketSession) NettyDataBufferFactory(org.springframework.core.io.buffer.NettyDataBufferFactory) URI(java.net.URI) ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse) HandshakeInfo(org.springframework.web.reactive.socket.HandshakeInfo)

Example 5 with WebSocketHandler

use of org.springframework.web.reactive.socket.WebSocketHandler in project spring-framework by spring-projects.

the class UndertowRequestUpgradeStrategy method upgrade.

@Override
public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler, @Nullable String subProtocol, Supplier<HandshakeInfo> handshakeInfoFactory) {
    HttpServerExchange httpExchange = ServerHttpRequestDecorator.getNativeRequest(exchange.getRequest());
    Set<String> protocols = (subProtocol != null ? Collections.singleton(subProtocol) : Collections.emptySet());
    Hybi13Handshake handshake = new Hybi13Handshake(protocols, false);
    List<Handshake> handshakes = Collections.singletonList(handshake);
    HandshakeInfo handshakeInfo = handshakeInfoFactory.get();
    DataBufferFactory bufferFactory = exchange.getResponse().bufferFactory();
    // Trigger WebFlux preCommit actions and upgrade
    return exchange.getResponse().setComplete().then(Mono.deferContextual(contextView -> {
        DefaultCallback callback = new DefaultCallback(handshakeInfo, ContextWebSocketHandler.decorate(handler, contextView), bufferFactory);
        try {
            new WebSocketProtocolHandshakeHandler(handshakes, callback).handleRequest(httpExchange);
        } catch (Exception ex) {
            return Mono.error(ex);
        }
        return Mono.empty();
    }));
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) HandshakeInfo(org.springframework.web.reactive.socket.HandshakeInfo) HttpServerExchange(io.undertow.server.HttpServerExchange) Hybi13Handshake(io.undertow.websockets.core.protocol.version13.Hybi13Handshake) RequestUpgradeStrategy(org.springframework.web.reactive.socket.server.RequestUpgradeStrategy) Set(java.util.Set) Mono(reactor.core.publisher.Mono) WebSocketConnectionCallback(io.undertow.websockets.WebSocketConnectionCallback) WebSocketProtocolHandshakeHandler(io.undertow.websockets.WebSocketProtocolHandshakeHandler) Supplier(java.util.function.Supplier) UndertowWebSocketHandlerAdapter(org.springframework.web.reactive.socket.adapter.UndertowWebSocketHandlerAdapter) ServerWebExchange(org.springframework.web.server.ServerWebExchange) List(java.util.List) UndertowWebSocketSession(org.springframework.web.reactive.socket.adapter.UndertowWebSocketSession) WebSocketHttpExchange(io.undertow.websockets.spi.WebSocketHttpExchange) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) Handshake(io.undertow.websockets.core.protocol.Handshake) WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) ServerHttpRequestDecorator(org.springframework.http.server.reactive.ServerHttpRequestDecorator) Nullable(org.springframework.lang.Nullable) WebSocketHandler(org.springframework.web.reactive.socket.WebSocketHandler) ContextWebSocketHandler(org.springframework.web.reactive.socket.adapter.ContextWebSocketHandler) Collections(java.util.Collections) Hybi13Handshake(io.undertow.websockets.core.protocol.version13.Hybi13Handshake) WebSocketProtocolHandshakeHandler(io.undertow.websockets.WebSocketProtocolHandshakeHandler) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) HandshakeInfo(org.springframework.web.reactive.socket.HandshakeInfo) Hybi13Handshake(io.undertow.websockets.core.protocol.version13.Hybi13Handshake) Handshake(io.undertow.websockets.core.protocol.Handshake)

Aggregations

WebSocketHandler (org.springframework.web.reactive.socket.WebSocketHandler)9 HandshakeInfo (org.springframework.web.reactive.socket.HandshakeInfo)7 Mono (reactor.core.publisher.Mono)6 Supplier (java.util.function.Supplier)5 Nullable (org.springframework.lang.Nullable)5 RequestUpgradeStrategy (org.springframework.web.reactive.socket.server.RequestUpgradeStrategy)4 ServerWebExchange (org.springframework.web.server.ServerWebExchange)4 URI (java.net.URI)3 DataBufferFactory (org.springframework.core.io.buffer.DataBufferFactory)3 NettyDataBufferFactory (org.springframework.core.io.buffer.NettyDataBufferFactory)3 ServerHttpRequestDecorator (org.springframework.http.server.reactive.ServerHttpRequestDecorator)3 ServerHttpResponse (org.springframework.http.server.reactive.ServerHttpResponse)3 ServerHttpResponseDecorator (org.springframework.http.server.reactive.ServerHttpResponseDecorator)3 Assert (org.springframework.util.Assert)3 ContextWebSocketHandler (org.springframework.web.reactive.socket.adapter.ContextWebSocketHandler)3 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)2 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)2 Collections (java.util.Collections)2 HashMap (java.util.HashMap)2 List (java.util.List)2