org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient Java Examples

The following examples show how to use org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractWebSocketIntegrationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Parameters(name = "client[{0}] - server [{1}]")
public static Object[][] arguments() throws IOException {

	WebSocketClient[] clients = new WebSocketClient[] {
			new TomcatWebSocketClient(),
			new JettyWebSocketClient(),
			new ReactorNettyWebSocketClient(),
			new UndertowWebSocketClient(Xnio.getInstance().createWorker(OptionMap.EMPTY))
	};

	Map<HttpServer, Class<?>> servers = new LinkedHashMap<>();
	servers.put(new TomcatHttpServer(TMP_DIR.getAbsolutePath(), WsContextListener.class), TomcatConfig.class);
	servers.put(new JettyHttpServer(), JettyConfig.class);
	servers.put(new ReactorHttpServer(), ReactorNettyConfig.class);
	servers.put(new UndertowHttpServer(), UndertowConfig.class);

	Flux<WebSocketClient> f1 = Flux.fromArray(clients).concatMap(c -> Flux.just(c).repeat(servers.size()));
	Flux<HttpServer> f2 = Flux.fromIterable(servers.keySet()).repeat(clients.length);
	Flux<Class<?>> f3 = Flux.fromIterable(servers.values()).repeat(clients.length);

	return Flux.zip(f1, f2, f3).map(Tuple3::toArray).collectList().block()
			.toArray(new Object[clients.length * servers.size()][2]);
}
 
Example #2
Source File: AbstractWebSocketIntegrationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Parameters(name = "client[{0}] - server [{1}]")
public static Object[][] arguments() throws IOException {

	WebSocketClient[] clients = new WebSocketClient[] {
			new TomcatWebSocketClient(),
			new JettyWebSocketClient(),
			new ReactorNettyWebSocketClient(),
			new UndertowWebSocketClient(Xnio.getInstance().createWorker(OptionMap.EMPTY))
	};

	Map<HttpServer, Class<?>> servers = new LinkedHashMap<>();
	servers.put(new TomcatHttpServer(TMP_DIR.getAbsolutePath(), WsContextListener.class), TomcatConfig.class);
	servers.put(new JettyHttpServer(), JettyConfig.class);
	servers.put(new ReactorHttpServer(), ReactorNettyConfig.class);
	servers.put(new UndertowHttpServer(), UndertowConfig.class);

	Flux<WebSocketClient> f1 = Flux.fromArray(clients).concatMap(c -> Flux.just(c).repeat(servers.size()));
	Flux<HttpServer> f2 = Flux.fromIterable(servers.keySet()).repeat(clients.length);
	Flux<Class<?>> f3 = Flux.fromIterable(servers.values()).repeat(clients.length);

	return Flux.zip(f1, f2, f3).map(Tuple3::toArray).collectList().block()
			.toArray(new Object[clients.length * servers.size()][2]);
}
 
Example #3
Source File: WebSocketApplication.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 6 votes vote down vote up
@Bean
public CommandLineRunner commandLineRunner() {
    return (args) -> {
        ReactorNettyWebSocketClient client = new ReactorNettyWebSocketClient();

        client.execute(
                URI.create("http://localhost:8080/ws/echo"),
                session -> Flux
                        .interval(Duration.ofMillis(100))
                        .map(String::valueOf)
                        .map(session::textMessage)
                        .as(session::send)
              )
              .subscribe();
    };
}
 
Example #4
Source File: WsClient.java    From reactor-workshop with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws URISyntaxException, InterruptedException {
    WebSocketClient client = new ReactorNettyWebSocketClient();

    URI url = new URI("ws://localhost:8080/time");
    final Mono<Void> reqResp = client
            .execute(url, session -> {
                Flux<WebSocketMessage> outMessages = Flux
                        .interval(Duration.ofSeconds(1))
                        .take(10)
                        .map(x -> "Message " + x)
                        .doOnNext(x -> log.info("About to send '{}'", x))
                        .map(session::textMessage);
                Mono<Void> receiving = session
                        .receive()
                        .map(WebSocketMessage::getPayloadAsText)
                        .doOnNext(x -> log.info("Received '{}'", x))
                        .then();
                return session.send(outMessages).mergeWith(receiving).then();
            });

    final Disposable disposable = reqResp.subscribe();
    TimeUnit.SECONDS.sleep(20);
    disposable.dispose();
}
 
Example #5
Source File: WSClient.java    From springboot-learning-example with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] args) {
    final WebSocketClient client = new ReactorNettyWebSocketClient();
    client.execute(URI.create("ws://localhost:8080/echo"), session ->
            session.send(Flux.just(session.textMessage("你好")))
                    .thenMany(session.receive().take(1).map(WebSocketMessage::getPayloadAsText))
                    .doOnNext(System.out::println)
                    .then())
            .block(Duration.ofMillis(5000));
}
 
Example #6
Source File: WebSocketIntegrationTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
	this.client = new ReactorNettyWebSocketClient();

	this.server = new ReactorHttpServer();
	this.server.setHandler(createHttpHandler());
	this.server.afterPropertiesSet();
	this.server.start();

	// Set dynamically chosen port
	this.serverPort = this.server.getPort();

	if (this.client instanceof Lifecycle) {
		((Lifecycle) this.client).start();
	}

	this.gatewayContext = new SpringApplicationBuilder(GatewayConfig.class)
			.properties("ws.server.port:" + this.serverPort, "server.port=0",
					"spring.jmx.enabled=false")
			.run();

	ConfigurableEnvironment env = this.gatewayContext
			.getBean(ConfigurableEnvironment.class);
	this.gatewayPort = Integer.valueOf(env.getProperty("local.server.port"));
}
 
Example #7
Source File: ReactiveJavaClientWebSocket.java    From tutorials with MIT License 6 votes vote down vote up
public static void main(String[] args) throws InterruptedException {

    WebSocketClient client = new ReactorNettyWebSocketClient();
    client.execute(
      URI.create("ws://localhost:8080/event-emitter"), 
      session -> session.send(
        Mono.just(session.textMessage("event-spring-reactive-client-websocket")))
        .thenMany(session.receive()
          .map(WebSocketMessage::getPayloadAsText)
          .log())
        .then())
        .block(Duration.ofSeconds(10L));
}
 
Example #8
Source File: WebSocketDemoClient.java    From spring-reactive-sample with GNU General Public License v3.0 5 votes vote down vote up
public static final void main(String[] args) throws URISyntaxException {

        WebSocketClient client = new ReactorNettyWebSocketClient();
//        client.execute(new URI("ws://localhost:8080/echo"), (WebSocketSession session) -> {
//            session.send().log().;
//        });
        
        int count = 100;
		Flux<String> input = Flux.range(1, count).map(index -> "msg-" + index);
		ReplayProcessor<Object> output = ReplayProcessor.create(count);

		client.execute(new URI("ws://localhost:8080/echo"),
				session -> {
					log.debug("Starting to send messages");
					return session
							.send(input.doOnNext(s -> log.debug("outbound " + s)).map(session::textMessage))
							.thenMany(session.receive().take(count).map(WebSocketMessage::getPayloadAsText))
							.subscribeWith(output)
							.doOnNext(s -> log.debug("inbound " + s))
							.then()
							.doOnTerminate((aVoid, ex) ->
									log.debug("Done with " + (ex != null ? ex.getMessage() : "success")));
				})
				.block(Duration.ofMillis(5000));

//		assertEquals(input.collectList().block(Duration.ofMillis(5000)),
//				output.collectList().block(Duration.ofMillis(5000)));
//        client.execute(new URI("ws://localhost:8080/echo")), session -> {
//            session.
//        }
//        ).blockMillis(5000);
    }
 
Example #9
Source File: GatewayAutoConfiguration.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Bean
public ReactorNettyWebSocketClient reactorNettyWebSocketClient(
		HttpClientProperties properties, HttpClient httpClient) {
	ReactorNettyWebSocketClient webSocketClient = new ReactorNettyWebSocketClient(
			httpClient);
	if (properties.getWebsocket().getMaxFramePayloadLength() != null) {
		webSocketClient.setMaxFramePayloadLength(
				properties.getWebsocket().getMaxFramePayloadLength());
	}
	webSocketClient.setHandlePing(properties.getWebsocket().isProxyPing());
	return webSocketClient;
}
 
Example #10
Source File: EmployeeWebSocketClient.java    From tutorials with MIT License 5 votes vote down vote up
public static void main(String[] args) {

        WebSocketClient client = new ReactorNettyWebSocketClient();
        
        client.execute(URI.create("ws://localhost:8080/employee-feed"), session -> session.receive()
            .map(WebSocketMessage::getPayloadAsText)
            .doOnNext(System.out::println)
            .then())
            .block(); // to subscribe and return the value
    }
 
Example #11
Source File: ClientConfiguration.java    From sample-webflux-websocket-netty with Apache License 2.0 4 votes vote down vote up
@Bean
public WebSocketClient webSocketClient()
{
	return new ReactorNettyWebSocketClient();
}
 
Example #12
Source File: ServiceInstanceLogStreamingTest.java    From spring-cloud-app-broker with Apache License 2.0 4 votes vote down vote up
private Disposable connectToLogsStreamEndpoint() {
	URI uri = URI.create("ws://localhost:" + port + "/logs/" + serviceInstanceId + "/stream");

	WebSocketClient client = new ReactorNettyWebSocketClient();
	return client.execute(uri, getWebSocketHandler()).subscribe();
}
 
Example #13
Source File: GatewayAutoConfigurationTests.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
@Test
public void nettyHttpClientConfigured() {
	new ReactiveWebApplicationContextRunner()
			.withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class,
					MetricsAutoConfiguration.class,
					SimpleMetricsExportAutoConfiguration.class,
					GatewayAutoConfiguration.class, HttpClientCustomizedConfig.class))
			.withPropertyValues(
					"spring.cloud.gateway.httpclient.ssl.use-insecure-trust-manager=true",
					"spring.cloud.gateway.httpclient.connect-timeout=10",
					"spring.cloud.gateway.httpclient.response-timeout=10s",
					"spring.cloud.gateway.httpclient.pool.type=fixed",
					// greather than integer max value
					"spring.cloud.gateway.httpclient.max-initial-line-length=2147483647",
					"spring.cloud.gateway.httpclient.proxy.host=myhost",
					"spring.cloud.gateway.httpclient.websocket.max-frame-payload-length=1024")
			.run(context -> {
				assertThat(context).hasSingleBean(HttpClient.class);
				HttpClient httpClient = context.getBean(HttpClient.class);
				HttpClientProperties properties = context
						.getBean(HttpClientProperties.class);
				assertThat(properties.getMaxInitialLineLength().toBytes())
						.isLessThanOrEqualTo(Integer.MAX_VALUE);
				/*
				 * FIXME: 2.1.0 HttpClientOptions options = httpClient.options();
				 *
				 * PoolResources poolResources = options.getPoolResources();
				 * assertThat(poolResources).isNotNull(); //TODO: howto test
				 * PoolResources
				 *
				 * ClientProxyOptions proxyOptions = options.getProxyOptions();
				 * assertThat(proxyOptions).isNotNull();
				 * assertThat(proxyOptions.getAddress().get().getHostName()).isEqualTo
				 * ("myhost");
				 *
				 * SslContext sslContext = options.sslContext();
				 * assertThat(sslContext).isNotNull();
				 */
				// TODO: howto test SslContext
				assertThat(context)
						.hasSingleBean(ReactorNettyRequestUpgradeStrategy.class);
				ReactorNettyRequestUpgradeStrategy upgradeStrategy = context
						.getBean(ReactorNettyRequestUpgradeStrategy.class);
				assertThat(upgradeStrategy.getMaxFramePayloadLength())
						.isEqualTo(1024);
				assertThat(upgradeStrategy.getHandlePing()).isTrue();
				assertThat(context).hasSingleBean(ReactorNettyWebSocketClient.class);
				ReactorNettyWebSocketClient webSocketClient = context
						.getBean(ReactorNettyWebSocketClient.class);
				assertThat(webSocketClient.getMaxFramePayloadLength())
						.isEqualTo(1024);
				HttpClientCustomizedConfig config = context
						.getBean(HttpClientCustomizedConfig.class);
				assertThat(config.called.get()).isTrue();
			});
}
 
Example #14
Source File: DividePluginConfiguration.java    From soul with Apache License 2.0 2 votes vote down vote up
/**
 * Reactor netty web socket client reactor netty web socket client.
 *
 * @return the reactor netty web socket client
 */
@Bean
public ReactorNettyWebSocketClient reactorNettyWebSocketClient() {
    return new ReactorNettyWebSocketClient();
}