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

The following examples show how to use org.springframework.web.reactive.socket.client.WebSocketClient. 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: 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 #2
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 #3
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 #4
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 #5
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 #6
Source File: WebSocketPlugin.java    From soul with Apache License 2.0 5 votes vote down vote up
/**
 * Instantiates a new Soul web socket handler.
 *
 * @param url       the url
 * @param client    the client
 * @param headers   the headers
 * @param protocols the protocols
 */
SoulWebSocketHandler(final URI url, final WebSocketClient client,
                     final HttpHeaders headers,
                     final List<String> protocols) {
    this.client = client;
    this.url = url;
    this.headers = headers;
    if (protocols != null) {
        this.subProtocols = protocols;
    } else {
        this.subProtocols = Collections.emptyList();
    }
}
 
Example #7
Source File: ClientLogic.java    From sample-webflux-websocket-netty with Apache License 2.0 5 votes vote down vote up
public Disposable start(WebSocketClient webSocketClient, URI uri, ClientWebSocketHandler clientWebSocketHandler)
{		
	clientWebSocketHandler
		.connected()
		.subscribe(this::doLogic);
	
	Disposable clientConnection =
		webSocketClient
			.execute(uri, clientWebSocketHandler)
			.subscribeOn(Schedulers.elastic())
			.subscribe();	
	
	return clientConnection;
}
 
Example #8
Source File: ClientLogicTest.java    From sample-webflux-websocket-netty with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp()
{
	webSocketClient = Mockito.mock(WebSocketClient.class);
	clientWebSocketHandler = Mockito.mock(ClientWebSocketHandler.class);
	sessionHandler = Mockito.mock(WebSocketSessionHandler.class);
	session = Mockito.mock(WebSocketSession.class);
}
 
Example #9
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 #10
Source File: GatewayAutoConfiguration.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Bean
public WebsocketRoutingFilter websocketRoutingFilter(WebSocketClient webSocketClient,
		WebSocketService webSocketService,
		ObjectProvider<List<HttpHeadersFilter>> headersFilters) {
	return new WebsocketRoutingFilter(webSocketClient, webSocketService,
			headersFilters);
}
 
Example #11
Source File: WebsocketRoutingFilter.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
public WebsocketRoutingFilter(WebSocketClient webSocketClient,
		WebSocketService webSocketService,
		ObjectProvider<List<HttpHeadersFilter>> headersFiltersProvider) {
	this.webSocketClient = webSocketClient;
	this.webSocketService = webSocketService;
	this.headersFiltersProvider = headersFiltersProvider;
}
 
Example #12
Source File: WebsocketRoutingFilter.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
ProxyWebSocketHandler(URI url, WebSocketClient client, HttpHeaders headers,
		List<String> protocols) {
	this.client = client;
	this.url = url;
	this.headers = headers;
	if (protocols != null) {
		this.subProtocols = protocols;
	}
	else {
		this.subProtocols = Collections.emptyList();
	}
}
 
Example #13
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 #14
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 #15
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 #16
Source File: TestBase.java    From vertx-spring-boot with Apache License 2.0 4 votes vote down vote up
/**
 * Get a preconfigured WebSocketClient.
 */
protected WebSocketClient getWebSocketClient() {
    return getBean(VertxWebSocketClient.class);
}
 
Example #17
Source File: DividePluginConfiguration.java    From soul with Apache License 2.0 2 votes vote down vote up
/**
 * Web socket plugin web socket plugin.
 *
 * @param webSocketClient  the web socket client
 * @param webSocketService the web socket service
 * @return the web socket plugin
 */
@Bean
public WebSocketPlugin webSocketPlugin(final WebSocketClient webSocketClient, final WebSocketService webSocketService) {
    return new WebSocketPlugin(webSocketClient, webSocketService);
}
 
Example #18
Source File: WebSocketPlugin.java    From soul with Apache License 2.0 2 votes vote down vote up
/**
 * Instantiates a new Web socket plugin.
 *
 * @param webSocketClient  the web socket client
 * @param webSocketService the web socket service
 */
public WebSocketPlugin(final WebSocketClient webSocketClient, final WebSocketService webSocketService) {
    this.webSocketClient = webSocketClient;
    this.webSocketService = webSocketService;
}