├── src └── test │ ├── resources │ ├── index.html │ └── logback.xml │ └── java │ └── io │ └── spring │ └── workshop │ └── reactornetty │ ├── http │ ├── HttpCompressionTests.java │ ├── HttpEchoPathParamTests.java │ └── HttpEncodeAndDecodeJsonTests.java │ ├── udp │ ├── UdpSupportsReceivingDatagramTests.java │ └── UdpEchoTests.java │ └── tcp │ └── TcpSendFileTests.java ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── .gitignore ├── README.md ├── pom.xml ├── mvnw.cmd ├── mvnw └── docs ├── README.adoc └── index.html /src/test/resources/index.html: -------------------------------------------------------------------------------- 1 | HELLO -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/violetagg/reactor-netty-workshop/HEAD/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.4/apache-maven-3.8.4-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar 3 | -------------------------------------------------------------------------------- /src/test/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/**/target/ 5 | !**/src/test/**/target/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | !**/src/main/**/build/ 30 | !**/src/test/**/build/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Reactor Netty Workshop 2 | 3 | This repository hosts a complete workshop on `Reactor Netty`. 4 | 5 | ## Prerequisites 6 | 7 | * `Java 8` 8 | * `Java IDE` installed with `Maven` support 9 | 10 | ## How to start 11 | 12 | * Clone this repository (or fork it) 13 | * Import the project as `Maven` one in your `IDE` 14 | * Make sure that the language level is set to `Java 8` in your `IDE` project settings 15 | * [Follow the script](https://violetagg.github.io/reactor-netty-workshop/) 16 | (the source document is in the `docs` folder) to create `HTTP`/`TCP`/`UDP` server and client 17 | * Fix the `TODO` one by one in the tests under `io.spring.workshop.reactornetty` 18 | package in order to make the unit tests green 19 | * The solution is available in the `complete` branch for comparison. Each step of this workshop 20 | has its companion commit in the git history with a detailed commit message. 21 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | io.spring.workshop 7 | reactor-netty 8 | 1.0.0-SNAPSHOT 9 | 10 | 11 | UTF-8 12 | 8 13 | 8 14 | 15 | 16 | 17 | 18 | io.projectreactor.netty 19 | reactor-netty-core 20 | 1.3.0 21 | 22 | 23 | io.projectreactor.netty 24 | reactor-netty-http 25 | 1.3.0 26 | 27 | 28 | com.fasterxml.jackson.core 29 | jackson-databind 30 | 2.20.1 31 | 32 | 33 | ch.qos.logback 34 | logback-classic 35 | 1.2.13 36 | 37 | 38 | ch.qos.logback 39 | logback-core 40 | 1.2.13 41 | 42 | 43 | org.junit.jupiter 44 | junit-jupiter-api 45 | 5.14.1 46 | 47 | 48 | io.netty 49 | netty-pkitesting 50 | 4.2.7.Final 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /src/test/java/io/spring/workshop/reactornetty/http/HttpCompressionTests.java: -------------------------------------------------------------------------------- 1 | package io.spring.workshop.reactornetty.http; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import reactor.netty.DisposableServer; 5 | 6 | import static org.junit.jupiter.api.Assertions.assertEquals; 7 | import static org.junit.jupiter.api.Assertions.assertNotNull; 8 | 9 | /** 10 | * Learn how to create HTTP server and client 11 | * 12 | * @author Violeta Georgieva 13 | * @see HttpServer javadoc 14 | * @see HttpClient javadoc 15 | */ 16 | public class HttpCompressionTests { 17 | 18 | @Test 19 | public void httpCompressionTest() { 20 | // TODO 21 | // Task 1: 22 | // 1.1. Prepare the HTTP server 23 | // 1.2. Configure the port to which this server should bind 24 | // 1.3. Start the server in a blocking fashion and wait for it 25 | // to finish initializing 26 | // 27 | // Task 3: 28 | // 3.3. Apply a wire logger configuration 29 | // 3.4. Enable compression 30 | // 31 | // Task 4: 32 | // 4.1. Attach an IO handler to react on connected client 33 | // 4.2. As a response send some string 34 | DisposableServer server = null; 35 | 36 | assertNotNull(server); 37 | 38 | // TODO 39 | // Task 5: 40 | // 5.1. Prepare the HTTP client 41 | // 5.2. Obtain the server's port and provide it as a port to which this 42 | // client should connect 43 | // 5.3. Apply a wire logger configuration 44 | // 5.4. Enable compression 45 | // 5.5. Prepare a GET request 46 | // 5.6. Specify the path 47 | // 5.7. Receive the response, aggregate it and transform it to string 48 | // 5.8. Subscribe to the returned Mono and block 49 | String response = null; 50 | 51 | assertEquals("compressed response", response); 52 | 53 | // TODO 54 | // Task 2: 55 | // 2.1. Close the underlying channel opened by the HTTP server 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/test/java/io/spring/workshop/reactornetty/http/HttpEchoPathParamTests.java: -------------------------------------------------------------------------------- 1 | package io.spring.workshop.reactornetty.http; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import reactor.netty.DisposableServer; 5 | 6 | import static org.junit.jupiter.api.Assertions.assertEquals; 7 | import static org.junit.jupiter.api.Assertions.assertNotNull; 8 | 9 | /** 10 | * Learn how to create HTTP server and client 11 | * 12 | * @author Violeta Georgieva 13 | * @see HttpServer javadoc 14 | * @see HttpClient javadoc 15 | */ 16 | public class HttpEchoPathParamTests { 17 | 18 | @Test 19 | public void echoPathParamTest() { 20 | // TODO 21 | // Task 1: 22 | // 1.1. Prepare the HTTP server 23 | // 1.2. Configure the port to which this server should bind 24 | // 1.3. Start the server in a blocking fashion and wait for it 25 | // to finish initializing 26 | // 27 | // Task 3: 28 | // 3.3. Apply a wire logger configuration 29 | // 30 | // Task 4: 31 | // 4.1. Define that the server will respond to POST requests 32 | // 4.2. Define the expected URI 33 | // 4.3. Define path parameter 34 | // 4.4. As a response send the received request body, which 35 | // is transformed to string and concatenated with the path parameter 36 | DisposableServer server = null; 37 | 38 | assertNotNull(server); 39 | 40 | // TODO 41 | // Task 5: 42 | // 5.1. Prepare the HTTP client 43 | // 5.2. Obtain the server's port and provide it as a port to which this 44 | // client should connect 45 | // 5.3. Apply a wire logger configuration 46 | // 5.4. As specify header 'Content-Type: text/plain' 47 | // 5.5. Prepare a POST request 48 | // 5.6. Specify the path and include path parameter 49 | // 5.7. Send some string as a request body 50 | // 5.8. Receive the response, aggregate it and transform it to string 51 | // 5.9. Subscribe to the returned Mono and block 52 | String response = null; 53 | 54 | assertEquals("Hello World!", response); 55 | 56 | // TODO 57 | // Task 2: 58 | // 2.1. Close the underlying channel opened by the HTTP server 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/test/java/io/spring/workshop/reactornetty/udp/UdpSupportsReceivingDatagramTests.java: -------------------------------------------------------------------------------- 1 | package io.spring.workshop.reactornetty.udp; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import reactor.netty.Connection; 5 | import reactor.netty.resources.LoopResources; 6 | 7 | import java.util.concurrent.CountDownLatch; 8 | import java.util.concurrent.TimeUnit; 9 | 10 | import static org.junit.jupiter.api.Assertions.assertNotNull; 11 | import static org.junit.jupiter.api.Assertions.assertTrue; 12 | 13 | 14 | /** 15 | * Learn how to create UDP server 16 | * 17 | * @author Violeta Georgieva 18 | * @see UdpServer javadoc 19 | */ 20 | public class UdpSupportsReceivingDatagramTests { 21 | 22 | @Test 23 | public void supportsReceivingDatagramTest() throws Exception { 24 | // TODO 25 | // Task 1: 26 | // 1.1. Prepare the UDP server 27 | // 1.2. Configure the port to which this server should bind 28 | // 1.3. Bind the server 29 | // 1.4. Subscribe to the returned Mono and block 30 | // 1.5. Create a new simple LoopResources 31 | // 1.6. Configure the UDP server to run on this newly created LoopResources 32 | // 1.7. Apply a wire logger configuration 33 | // 34 | // Task 6: 35 | // 6.1. Attach an IO handler 36 | // 6.2. When receive a package, transform it to byte array 37 | // 6.3. On every emitted byte array, inspect the byte array's length 38 | // and if it is the expected size, decrement the count of the latch 39 | LoopResources loopResources = null; 40 | CountDownLatch latch = new CountDownLatch(4); 41 | Connection server1 = null; 42 | 43 | assertNotNull(server1); 44 | 45 | // TODO 46 | // Task 3: 47 | // 3.1. Prepare the UDP server 48 | // 3.2. Configure the port to which this server should bind 49 | // 3.3. Bind the server 50 | // 3.4. Subscribe to the returned Mono and block 51 | // 3.5. Create a new simple LoopResources 52 | // 3.6. Configure the UDP server to run on this newly created LoopResources 53 | // 3.7. Apply a wire logger configuration 54 | // 55 | // Task 5: 56 | // 5.1. As soon as bind operation completed successfully, open a DatagramChannel, 57 | // connect to the server1's port, send data and close the channel 58 | Connection server2 = null; 59 | 60 | assertNotNull(server2); 61 | 62 | assertTrue(latch.await(30, TimeUnit.SECONDS)); 63 | 64 | // TODO 65 | // Task 2: 66 | // 2.1. Close the underlying channel opened by the UDP server 67 | 68 | // TODO 69 | // Task 4: 70 | // 4.1. Close the underlying channel opened by the UDP server 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/test/java/io/spring/workshop/reactornetty/udp/UdpEchoTests.java: -------------------------------------------------------------------------------- 1 | package io.spring.workshop.reactornetty.udp; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import reactor.netty.Connection; 5 | import reactor.netty.resources.LoopResources; 6 | 7 | import java.util.concurrent.CountDownLatch; 8 | import java.util.concurrent.TimeUnit; 9 | 10 | import static org.junit.jupiter.api.Assertions.assertNotNull; 11 | import static org.junit.jupiter.api.Assertions.assertTrue; 12 | 13 | 14 | /** 15 | * Learn how to create UDP server and client 16 | * 17 | * @author Violeta Georgieva 18 | * @see UdpServer javadoc 19 | * @see UdpClient javadoc 20 | */ 21 | public class UdpEchoTests { 22 | 23 | @Test 24 | public void echoTest() throws Exception { 25 | // TODO 26 | // Task 1: 27 | // 1.1. Prepare the UDP server 28 | // 1.2. Configure the port to which this server should bind 29 | // 1.3. Bind the server 30 | // 1.4. Subscribe to the returned Mono and block 31 | // 32 | // Task 3: 33 | // 3.1. Create a new simple LoopResources 34 | // 3.2. Configure the UDP server to run on this newly created LoopResources 35 | // 3.3. Apply a wire logger configuration 36 | // 37 | // Task 4: 38 | // 4.1. Attach an IO handler to react on connected client 39 | // 4.2. When receive an object (io.netty.channel.socket.DatagramPacket), 40 | // transform it and send the new object to the client 41 | LoopResources loopResources = null; 42 | Connection server = null; 43 | 44 | assertNotNull(server); 45 | 46 | // TODO 47 | // Task 5: 48 | // 5.1. Prepare the UDP client 49 | // 5.2. Obtain the server's address and provide it as an address to which this 50 | // client should connect 51 | // 5.3. Connect the client 52 | // 5.4. Subscribe to the returned Mono and block 53 | // 54 | // Task 7: 55 | // 7.1. Create a new simple LoopResources 56 | // 7.2. Configure the UDP client to run on this newly created LoopResources 57 | // 7.3. Apply a wire logger configuration 58 | // 59 | // Task 8: 60 | // 8.1. Attach an IO handler 61 | // 8.2. Send a string over the wire 62 | // 8.3. When receive an object (io.netty.channel.socket.DatagramPacket), 63 | // inspect whether is it the expected reply and decrements the count of the latch 64 | CountDownLatch latch = new CountDownLatch(1); 65 | Connection client = null; 66 | 67 | assertNotNull(client); 68 | 69 | assertTrue(latch.await(30, TimeUnit.SECONDS)); 70 | 71 | // TODO 72 | // Task 2: 73 | // 2.1. Close the underlying channel opened by the UDP server 74 | 75 | // TODO 76 | // Task 6: 77 | // 6.1. Close the underlying channel opened by the UDP client 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/test/java/io/spring/workshop/reactornetty/tcp/TcpSendFileTests.java: -------------------------------------------------------------------------------- 1 | package io.spring.workshop.reactornetty.tcp; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import reactor.netty.Connection; 5 | import reactor.netty.DisposableServer; 6 | 7 | import java.util.concurrent.CountDownLatch; 8 | import java.util.concurrent.TimeUnit; 9 | 10 | import static org.junit.jupiter.api.Assertions.assertNotNull; 11 | import static org.junit.jupiter.api.Assertions.assertTrue; 12 | 13 | 14 | /** 15 | * Learn how to create TCP server and client 16 | * 17 | * @author Violeta Georgieva 18 | * @see TcpServer javadoc 19 | * @see TcpClient javadoc 20 | */ 21 | public class TcpSendFileTests { 22 | 23 | @Test 24 | public void sendFileTest() throws Exception { 25 | // TODO 26 | // Task 1: 27 | // 1.1. Prepare the TCP server 28 | // 1.2. Configure the port to which this server should bind 29 | // 1.3. Start the server in a blocking fashion and wait for it 30 | // to finish initializing 31 | // 32 | // Task 3: 33 | // 3.1. Enable SSL configuration with self singed certificate. 34 | // 3.3. Apply a wire logger configuration 35 | // 36 | // Task 4: 37 | // 4.1. Attach an IO handler to react on connected client 38 | // 4.2. When receive an object, transform it to string 39 | // (this will be name of the requested file) 40 | // 4.3. As a response send the requested file to the client 41 | DisposableServer server = null; 42 | 43 | assertNotNull(server); 44 | 45 | // TODO 46 | // Task 5: 47 | // 5.1. Prepare the TCP client 48 | // 5.2. Obtain the server's address and provide it as an address to which this 49 | // client should connect 50 | // 5.3. Block the client and return a Connection 51 | // 52 | // Task 7: 53 | // 7.1. Apply an SSL configuration customization via a preconfigured SslContext, 54 | // use SslContextBuilder for building SslContext, as a trust manager 55 | // use InsecureTrustManagerFactory 56 | // 7.3. Apply a wire logger configuration 57 | // 58 | // Task 8: 59 | // 8.1. Attach an IO handler 60 | // 8.2. Send the file name as string over the wire 61 | // 8.3. When receive a package, transform it to byte array 62 | // 8.4. Compare the received byte array with file's bytes 63 | // and if they are the same, decrement the count of the latch 64 | CountDownLatch latch = new CountDownLatch(1); 65 | Connection client = null; 66 | 67 | assertNotNull(client); 68 | 69 | assertTrue(latch.await(30, TimeUnit.SECONDS)); 70 | 71 | // TODO 72 | // Task 2: 73 | // 2.1. Close the underlying channel opened by the TCP server 74 | 75 | // TODO 76 | // Task 6: 77 | // 6.1. Close the underlying channel opened by the TCP client 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/test/java/io/spring/workshop/reactornetty/http/HttpEncodeAndDecodeJsonTests.java: -------------------------------------------------------------------------------- 1 | package io.spring.workshop.reactornetty.http; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import io.netty.buffer.ByteBuf; 5 | import io.netty.buffer.Unpooled; 6 | import org.junit.jupiter.api.BeforeEach; 7 | import org.junit.jupiter.api.Test; 8 | import reactor.netty.DisposableServer; 9 | 10 | import java.io.ByteArrayOutputStream; 11 | import java.util.List; 12 | import java.util.function.Function; 13 | 14 | import static org.junit.jupiter.api.Assertions.assertEquals; 15 | import static org.junit.jupiter.api.Assertions.assertNotNull; 16 | 17 | /** 18 | * Learn how to create HTTP server and client 19 | * 20 | * @author Violeta Georgieva 21 | * @see HttpServer javadoc 22 | * @see HttpClient javadoc 23 | */ 24 | public class HttpEncodeAndDecodeJsonTests { 25 | private Function, ByteBuf> jsonEncoder; 26 | private Function jsonDecoder; 27 | 28 | @BeforeEach 29 | public void setUp() { 30 | ObjectMapper mapper = new ObjectMapper(); 31 | 32 | jsonEncoder = pojo -> { 33 | try { 34 | ByteArrayOutputStream out = new ByteArrayOutputStream(); 35 | mapper.writeValue(out, pojo); 36 | return Unpooled.copiedBuffer(out.toByteArray()); 37 | } catch(Exception e) { 38 | throw new RuntimeException(e); 39 | } 40 | }; 41 | 42 | jsonDecoder = s -> { 43 | try { 44 | return mapper.readValue(s, Pojo[].class); 45 | } catch(Exception e) { 46 | throw new RuntimeException(e); 47 | } 48 | }; 49 | } 50 | 51 | @Test 52 | public void encodeAndDecodeJsonTest() { 53 | // TODO 54 | // Task 1: 55 | // 1.1. Prepare the HTTP server 56 | // 1.2. Configure the port to which this server should bind 57 | // 1.3. Start the server in a blocking fashion and wait for it 58 | // to finish initializing 59 | // 60 | // Task 3: 61 | // 3.3. Apply a wire logger configuration 62 | // 63 | // Task 4: 64 | // 4.1. Add to the request pipeline a new handler 'JsonObjectDecoder' 65 | // 4.2. When receive the request body, transform it to string 66 | // 4.3. Use the snippet below to do JSON decoding, prepare response as batches 67 | // and do JSON encoding 68 | // ---- 69 | // out.send(in.withConnection(c -> c.addHandler(new JsonObjectDecoder())) 70 | // .receive() 71 | // .asString() 72 | // .map(jsonDecoder) 73 | // .concatMap(Flux::fromArray) 74 | // .window(5) 75 | // .concatMap(w -> w.collectList().map(jsonEncoder)))) 76 | // ---- 77 | // 4.4. Send the response 78 | DisposableServer server = null; 79 | 80 | assertNotNull(server); 81 | 82 | // TODO 83 | // Task 5: 84 | // 5.1. Prepare the HTTP client 85 | // 5.2. Obtain the server's port and provide it as a port to which this 86 | // client should connect 87 | // 5.3. Apply a wire logger configuration 88 | // 5.4. Add to the request pipeline a new handler 'JsonObjectDecoder' 89 | // 5.5. Prepare a POST request 90 | // 5.6. Specify the path 91 | // 5.7. Send the snippet below as a request body. It will do JSON encoding 92 | // ---- 93 | // Flux.range(1, 10) 94 | // .map(i -> new Pojo("test " + i)) 95 | // .collectList() 96 | // .map(jsonEncoder) 97 | // ---- 98 | // 5.8. Receive the response, transform it to string and do JSON decoding 99 | // ---- 100 | // .asString() 101 | // .map(jsonDecoder) 102 | // .concatMap(Flux::fromArray) 103 | // ---- 104 | // 5.9. Subscribe to the returned Flux and block the last element 105 | Pojo response = null; 106 | 107 | assertEquals("test 10", response.getName()); 108 | 109 | // TODO 110 | // Task 2: 111 | // 2.1. Close the underlying channel opened by the HTTP server 112 | } 113 | 114 | private static final class Pojo { 115 | private String name; 116 | 117 | Pojo() { 118 | } 119 | 120 | Pojo(String name) { 121 | this.name = name; 122 | } 123 | 124 | public String getName() { 125 | return name; 126 | } 127 | 128 | public void setName(String name) { 129 | this.name = name; 130 | } 131 | 132 | @Override 133 | public String toString() { 134 | return "Pojo {" + "name='" + name + '\'' + '}'; 135 | } 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM https://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* 50 | if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 124 | 125 | FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 127 | ) 128 | 129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 131 | if exist %WRAPPER_JAR% ( 132 | if "%MVNW_VERBOSE%" == "true" ( 133 | echo Found %WRAPPER_JAR% 134 | ) 135 | ) else ( 136 | if not "%MVNW_REPOURL%" == "" ( 137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 138 | ) 139 | if "%MVNW_VERBOSE%" == "true" ( 140 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 141 | echo Downloading from: %DOWNLOAD_URL% 142 | ) 143 | 144 | powershell -Command "&{"^ 145 | "$webclient = new-object System.Net.WebClient;"^ 146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 148 | "}"^ 149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ 150 | "}" 151 | if "%MVNW_VERBOSE%" == "true" ( 152 | echo Finished downloading %WRAPPER_JAR% 153 | ) 154 | ) 155 | @REM End of extension 156 | 157 | @REM Provide a "standardized" way to retrieve the CLI args that will 158 | @REM work with both Windows and non-Windows executions. 159 | set MAVEN_CMD_LINE_ARGS=%* 160 | 161 | %MAVEN_JAVA_EXE% ^ 162 | %JVM_CONFIG_MAVEN_PROPS% ^ 163 | %MAVEN_OPTS% ^ 164 | %MAVEN_DEBUG_OPTS% ^ 165 | -classpath %WRAPPER_JAR% ^ 166 | "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ 167 | %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 168 | if ERRORLEVEL 1 goto error 169 | goto end 170 | 171 | :error 172 | set ERROR_CODE=1 173 | 174 | :end 175 | @endlocal & set ERROR_CODE=%ERROR_CODE% 176 | 177 | if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost 178 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 179 | if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" 180 | if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" 181 | :skipRcPost 182 | 183 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 184 | if "%MAVEN_BATCH_PAUSE%"=="on" pause 185 | 186 | if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% 187 | 188 | cmd /C exit /B %ERROR_CODE% 189 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # https://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /usr/local/etc/mavenrc ] ; then 40 | . /usr/local/etc/mavenrc 41 | fi 42 | 43 | if [ -f /etc/mavenrc ] ; then 44 | . /etc/mavenrc 45 | fi 46 | 47 | if [ -f "$HOME/.mavenrc" ] ; then 48 | . "$HOME/.mavenrc" 49 | fi 50 | 51 | fi 52 | 53 | # OS specific support. $var _must_ be set to either true or false. 54 | cygwin=false; 55 | darwin=false; 56 | mingw=false 57 | case "`uname`" in 58 | CYGWIN*) cygwin=true ;; 59 | MINGW*) mingw=true;; 60 | Darwin*) darwin=true 61 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 62 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 63 | if [ -z "$JAVA_HOME" ]; then 64 | if [ -x "/usr/libexec/java_home" ]; then 65 | export JAVA_HOME="`/usr/libexec/java_home`" 66 | else 67 | export JAVA_HOME="/Library/Java/Home" 68 | fi 69 | fi 70 | ;; 71 | esac 72 | 73 | if [ -z "$JAVA_HOME" ] ; then 74 | if [ -r /etc/gentoo-release ] ; then 75 | JAVA_HOME=`java-config --jre-home` 76 | fi 77 | fi 78 | 79 | if [ -z "$M2_HOME" ] ; then 80 | ## resolve links - $0 may be a link to maven's home 81 | PRG="$0" 82 | 83 | # need this for relative symlinks 84 | while [ -h "$PRG" ] ; do 85 | ls=`ls -ld "$PRG"` 86 | link=`expr "$ls" : '.*-> \(.*\)$'` 87 | if expr "$link" : '/.*' > /dev/null; then 88 | PRG="$link" 89 | else 90 | PRG="`dirname "$PRG"`/$link" 91 | fi 92 | done 93 | 94 | saveddir=`pwd` 95 | 96 | M2_HOME=`dirname "$PRG"`/.. 97 | 98 | # make it fully qualified 99 | M2_HOME=`cd "$M2_HOME" && pwd` 100 | 101 | cd "$saveddir" 102 | # echo Using m2 at $M2_HOME 103 | fi 104 | 105 | # For Cygwin, ensure paths are in UNIX format before anything is touched 106 | if $cygwin ; then 107 | [ -n "$M2_HOME" ] && 108 | M2_HOME=`cygpath --unix "$M2_HOME"` 109 | [ -n "$JAVA_HOME" ] && 110 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 111 | [ -n "$CLASSPATH" ] && 112 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 113 | fi 114 | 115 | # For Mingw, ensure paths are in UNIX format before anything is touched 116 | if $mingw ; then 117 | [ -n "$M2_HOME" ] && 118 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 119 | [ -n "$JAVA_HOME" ] && 120 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 121 | fi 122 | 123 | if [ -z "$JAVA_HOME" ]; then 124 | javaExecutable="`which javac`" 125 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 126 | # readlink(1) is not available as standard on Solaris 10. 127 | readLink=`which readlink` 128 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 129 | if $darwin ; then 130 | javaHome="`dirname \"$javaExecutable\"`" 131 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 132 | else 133 | javaExecutable="`readlink -f \"$javaExecutable\"`" 134 | fi 135 | javaHome="`dirname \"$javaExecutable\"`" 136 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 137 | JAVA_HOME="$javaHome" 138 | export JAVA_HOME 139 | fi 140 | fi 141 | fi 142 | 143 | if [ -z "$JAVACMD" ] ; then 144 | if [ -n "$JAVA_HOME" ] ; then 145 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 146 | # IBM's JDK on AIX uses strange locations for the executables 147 | JAVACMD="$JAVA_HOME/jre/sh/java" 148 | else 149 | JAVACMD="$JAVA_HOME/bin/java" 150 | fi 151 | else 152 | JAVACMD="`\\unset -f command; \\command -v java`" 153 | fi 154 | fi 155 | 156 | if [ ! -x "$JAVACMD" ] ; then 157 | echo "Error: JAVA_HOME is not defined correctly." >&2 158 | echo " We cannot execute $JAVACMD" >&2 159 | exit 1 160 | fi 161 | 162 | if [ -z "$JAVA_HOME" ] ; then 163 | echo "Warning: JAVA_HOME environment variable is not set." 164 | fi 165 | 166 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 167 | 168 | # traverses directory structure from process work directory to filesystem root 169 | # first directory with .mvn subdirectory is considered project base directory 170 | find_maven_basedir() { 171 | 172 | if [ -z "$1" ] 173 | then 174 | echo "Path not specified to find_maven_basedir" 175 | return 1 176 | fi 177 | 178 | basedir="$1" 179 | wdir="$1" 180 | while [ "$wdir" != '/' ] ; do 181 | if [ -d "$wdir"/.mvn ] ; then 182 | basedir=$wdir 183 | break 184 | fi 185 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 186 | if [ -d "${wdir}" ]; then 187 | wdir=`cd "$wdir/.."; pwd` 188 | fi 189 | # end of workaround 190 | done 191 | echo "${basedir}" 192 | } 193 | 194 | # concatenates all lines of a file 195 | concat_lines() { 196 | if [ -f "$1" ]; then 197 | echo "$(tr -s '\n' ' ' < "$1")" 198 | fi 199 | } 200 | 201 | BASE_DIR=`find_maven_basedir "$(pwd)"` 202 | if [ -z "$BASE_DIR" ]; then 203 | exit 1; 204 | fi 205 | 206 | ########################################################################################## 207 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 208 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 209 | ########################################################################################## 210 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 211 | if [ "$MVNW_VERBOSE" = true ]; then 212 | echo "Found .mvn/wrapper/maven-wrapper.jar" 213 | fi 214 | else 215 | if [ "$MVNW_VERBOSE" = true ]; then 216 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 217 | fi 218 | if [ -n "$MVNW_REPOURL" ]; then 219 | jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 220 | else 221 | jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 222 | fi 223 | while IFS="=" read key value; do 224 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 225 | esac 226 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 227 | if [ "$MVNW_VERBOSE" = true ]; then 228 | echo "Downloading from: $jarUrl" 229 | fi 230 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 231 | if $cygwin; then 232 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` 233 | fi 234 | 235 | if command -v wget > /dev/null; then 236 | if [ "$MVNW_VERBOSE" = true ]; then 237 | echo "Found wget ... using wget" 238 | fi 239 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 240 | wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" 241 | else 242 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" 243 | fi 244 | elif command -v curl > /dev/null; then 245 | if [ "$MVNW_VERBOSE" = true ]; then 246 | echo "Found curl ... using curl" 247 | fi 248 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 249 | curl -o "$wrapperJarPath" "$jarUrl" -f 250 | else 251 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f 252 | fi 253 | 254 | else 255 | if [ "$MVNW_VERBOSE" = true ]; then 256 | echo "Falling back to using Java to download" 257 | fi 258 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 259 | # For Cygwin, switch paths to Windows format before running javac 260 | if $cygwin; then 261 | javaClass=`cygpath --path --windows "$javaClass"` 262 | fi 263 | if [ -e "$javaClass" ]; then 264 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 265 | if [ "$MVNW_VERBOSE" = true ]; then 266 | echo " - Compiling MavenWrapperDownloader.java ..." 267 | fi 268 | # Compiling the Java class 269 | ("$JAVA_HOME/bin/javac" "$javaClass") 270 | fi 271 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 272 | # Running the downloader 273 | if [ "$MVNW_VERBOSE" = true ]; then 274 | echo " - Running MavenWrapperDownloader.java ..." 275 | fi 276 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 277 | fi 278 | fi 279 | fi 280 | fi 281 | ########################################################################################## 282 | # End of extension 283 | ########################################################################################## 284 | 285 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 286 | if [ "$MVNW_VERBOSE" = true ]; then 287 | echo $MAVEN_PROJECTBASEDIR 288 | fi 289 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 290 | 291 | # For Cygwin, switch paths to Windows format before running java 292 | if $cygwin; then 293 | [ -n "$M2_HOME" ] && 294 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 295 | [ -n "$JAVA_HOME" ] && 296 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 297 | [ -n "$CLASSPATH" ] && 298 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 299 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 300 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 301 | fi 302 | 303 | # Provide a "standardized" way to retrieve the CLI args that will 304 | # work with both Windows and non-Windows executions. 305 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 306 | export MAVEN_CMD_LINE_ARGS 307 | 308 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 309 | 310 | exec "$JAVACMD" \ 311 | $MAVEN_OPTS \ 312 | $MAVEN_DEBUG_OPTS \ 313 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 314 | "-Dmaven.home=${M2_HOME}" \ 315 | "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 316 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 317 | -------------------------------------------------------------------------------- /docs/README.adoc: -------------------------------------------------------------------------------- 1 | = Reactor Netty Workshop 2 | Violeta Georgieva - VMware 3 | :sectanchors: true 4 | :source-highlighter: prettify 5 | :icons: font 6 | :toc: 7 | :reactor-core: 3.8.0 8 | :reactor-netty: 1.3.0 9 | 10 | This repository hosts a complete workshop on `Reactor Netty`. 11 | 12 | When finishing the workshop one will know how to create and utilize: 13 | 14 | * `UDP` server and client 15 | * `TCP` server and client 16 | * `HTTP` server and client 17 | 18 | Reference documentation can be useful while creating those servers and clients: 19 | 20 | * https://projectreactor.io/docs/netty/release/api/[Reactor Netty javadoc] 21 | * https://projectreactor.io/docs/core/release/api/[Reactor Core javadoc] 22 | * https://netty.io/wiki/index.html[Netty documentation] (Reactor Netty uses Netty 4.2.x) 23 | 24 | == Prerequisites 25 | 26 | * `Java 8` 27 | * `Java IDE` installed with `Maven` support 28 | 29 | == How to start 30 | 31 | * Clone/fork this repository https://github.com/violetagg/reactor-netty-workshop 32 | * Import the project as `Maven` one in your `IDE` 33 | * Make sure that the language level is set to `Java 8` in your `IDE` project settings 34 | * Follow this script to create `HTTP`/`TCP`/`UDP` server and client 35 | * Fix the `TODO` one by one in the tests under `io.spring.workshop.reactornetty` 36 | package in order to make the unit tests green 37 | * The solution is available in the `complete` branch for comparison. Each step of this workshop 38 | has its companion commit in the git history with a detailed commit message. 39 | 40 | == UDP server and client 41 | If one wants to utilize the `UDP` protocol one will need to create a `UDP` servers that can send packages 42 | to each other or even `UDP` clients that can connect to specific `UDP` servers. 43 | `Reactor Netty` provides easy to use and configure `UdpServer` and `UdpClient`, they hide most of the 44 | `Netty` functionality that is needed in order to create `UDP` server and client, and in addition add 45 | `Reactive Streams` backpressure. 46 | 47 | === Creating UDP server 48 | `UdpServer` allows to build, configure and materialize a `UDP` server. 49 | Invoking `UdpServer.create()` one can prepare the `UDP` server for configuration. Having already a `UdpServer` 50 | instance, one can start configuring the host, port, the IO handler etc. 51 | For configuration purposes, an immutable builder pattern is used. 52 | In the example below the `UDP` server will be bound on port `8080` and will not use a random port. 53 | 54 | [source, java] 55 | ---- 56 | UdpServer.create() // Prepares a UDP server for configuration. 57 | .port(0) // Configures the port number as zero, this will let the system 58 | // pick up an ephemeral port when binding the server. 59 | .port(8080)// Configures the port number as 8080. 60 | .bind() // Binds the UDP server and returns a Mono. 61 | .block(); // Blocks and waits the server to finish initialising. 62 | ---- 63 | 64 | When finished with the server configuration, invoking `UdpServer.bind()`, one will bind the server 65 | and `Mono` will be return, subscribing to this `Publisher` one can react 66 | on a successfully finished operation or handle issues that might happen. On the other hand 67 | cancelling this `Mono`, the underlying binding will be aborted. If one do not need to interact with the `Mono`, 68 | there is `UdpServer.bindNow(Duration)` which is a convenient method for binding the server and obtaining the 69 | `Connection`. 70 | The `Connection` that is emitted as a result of a successfully bound server, holds contextual information 71 | for the underlying channel and provides a non-blocking resource disposing API. 72 | Disposing resource is very important so once the server is not necessary anymore, it must be disposed 73 | by the user via `Connection.dispose()` or `Connection.disposeNow()`. The difference between these two methods is 74 | that the second one will release the resources and close the underlying channel in a blocking fashion. 75 | 76 | === Configuring UDP server 77 | ==== Configuring the Wire Logger 78 | There are use case when one wants to enable a wire logger in order to understand what's wrong with the server. 79 | For that purposes `UdpServer.wiretap` can be used and this will use `reactor.netty.udp.UdpServer` category 80 | with `DEBUG` level. There are also `UdpServer.wiretap(String)` and `UdpServer.wiretap(String, LogLevel)` so that 81 | one can change the category and the log level. 82 | 83 | ==== Configuring the Event Loop Group 84 | By default the `UDP` server will use Event Loop Group where the number of the worker threads will be 85 | the number of processors available to the runtime on init (but with a minimum value of 4). When 86 | one needs a different configuration, one of the `LoopResource.create` methods can be used in order to configure a new 87 | Event Loop Group. Once the Event Loop Group is configured, the new configuration can be provided using one of the 88 | `UdpServer.runOn`. 89 | 90 | === Add UDP server IO handler that will echo the received package 91 | `UdpServer.handle(BiFunction>)` should be used if one wants to attach IO 92 | handler that will process the incoming packages and will eventually send packages as reply. 93 | `UdpInbound` is used to receive bytes from the peer where `UdpInbound.receiveObject()` returns the pure inbound 94 | `Flux`, while `UdpInbound.receive()` returns `ByteBufFlux` which provides an extra API to handle the incoming traffic. 95 | `UdpOutbound` is used to send bytes to the peer, listen for any error returned by the write operation 96 | and close on terminal signal (complete|error). If more than one `Publisher` is attached 97 | (multiple calls to `UdpOutbound.send*` methods), completion occurs when all publishers complete. 98 | The `Publisher` that has to be returned as a result represents the sequence of the operations that will be 99 | applied for the incoming and outgoing traffic. 100 | The packages that will be received and that will be send are handled by `io.netty.channel.socket.DatagramPacket`. 101 | For example if one wants to transform an incoming package and then to prepare a new one for sending, the snippet bellow 102 | can be used: 103 | 104 | [source, java] 105 | ---- 106 | if (o instanceof DatagramPacket) { 107 | // Incoming DatagramPacket 108 | DatagramPacket p = (DatagramPacket) o; 109 | ByteBuf buf1 = Unpooled.copiedBuffer("Hello ", CharsetUtil.UTF_8); 110 | // Creates a new ByteBuf using the incoming DatagramPacket content. 111 | ByteBuf buf2 = Unpooled.copiedBuffer(buf1, p.content() 112 | .retain()); 113 | // Creates a new DatagramPacket with the ByteBuf and the sender 114 | // information from the incoming DatagramPacket. 115 | return new DatagramPacket(buf2, p.sender()); 116 | } 117 | ---- 118 | 119 | === Creating UDP client 120 | `UdpClient` allows to build, configure and materialize a `UDP` client. 121 | Invoking `UdpClient.create()` one can prepare the `UDP` client for configuration. Having already a `UdpClient` 122 | instance, one can start configuring the host, port, the IO handler etc. 123 | For configuration purposes, the same immutable builder pattern is used as in `UdpServer`. 124 | 125 | When finished with the client configuration, invoking `UdpClient.connect()`, one will connect the client 126 | and `Mono` will be return, subscribing to this `Publisher` one can react 127 | on a successfully finished operation or handle issues that might happen. On the other hand 128 | cancelling this `Mono`, the underlying connecting operation will be aborted. If one do not need to interact with the 129 | `Mono`, there is `UdpClient.connectNow(Duration)` which is a convenient method for connecting the client and obtaining 130 | the `Connection`. 131 | As already described in the `UDP` server section, disposing the resources can be done via `Connection.dispose()` 132 | or `Connection.disposeNow()`. 133 | 134 | === Configuring UDP client 135 | ==== Configuring the Wire Logger 136 | `UdpClient.wiretap` can be used for wire logging and this will use `reactor.netty.udp.UdpClient` category 137 | with `DEBUG` level. There are also `UdpClient.wiretap(String)` and `UdpClient.wiretap(String, LogLevel)` so that 138 | one can change the category and the log level. 139 | 140 | ==== Configuring the Event Loop Group 141 | The default configuration for the Event Loop Group is the same as in `UDP` server. 142 | When one needs a different configuration, `UdpClient.runOn` methods can be used. 143 | 144 | === Add UDP client IO handler that will send a package and will react on an incoming packages 145 | `UdpClient.handle(BiFunction>)` should be used if one wants to attach IO 146 | handler that will process the incoming packages and will eventually send packages as reply. 147 | Here as a convenience `UdpOutbound.send*` (e.g. `UdpOutbound.sendString`) methods can be used instead of 148 | `UdpOutbound.sendObject` as the client is connected to exactly one `UDP` server. The same is also for 149 | using `UdpInbound.receive()` instead of `UdpInbound.receiveObject()`. 150 | 151 | === Utilize Mono 152 | In the section for the `UDP` server creation was described that as a result of `UdpServer.bind` one will 153 | receive `Mono` which will emit (complete|error) signals. 154 | Utilizing this `Mono` one can send a datagram package (the snippet below) as soon as the `UDP` server is 155 | bound successfully. 156 | 157 | [source, java] 158 | ---- 159 | DatagramChannel udp = DatagramChannel.open(); 160 | udp.configureBlocking(true); 161 | udp.connect(new InetSocketAddress(server1.address().getPort())); 162 | 163 | byte[] data = new byte[1024]; 164 | new Random().nextBytes(data); 165 | for (int i = 0; i < 4; i++) { 166 | udp.write(ByteBuffer.wrap(data)); 167 | } 168 | 169 | udp.close(); 170 | ---- 171 | 172 | == TCP server and client 173 | If one wants to utilize the `TCP` protocol one will need to create a `TCP` servers that can send packages 174 | to the connected clients or `TCP` clients that can connect to specific `TCP` servers. 175 | `Reactor Netty` provides easy to use and configure `TcpServer` and `TcpClient`, they hide most of the 176 | `Netty` functionality that is needed in order to create with `TCP` server and client, and in addition add 177 | `Reactive Streams` backpressure. 178 | 179 | === Creating TCP server 180 | `TcpServer` allows to build, configure and materialize a `TCP` server. 181 | Invoking `TcpServer.create()` one can prepare the `TCP` server for configuration. Having already a `TcpServer` 182 | instance, one can start configuring the host, port, the IO handler etc. 183 | For configuration purposes, the same immutable builder pattern is used as in `UdpServer`. 184 | 185 | When finished with the server configuration, invoking `TcpServer.bind`, one will bind the server 186 | and `Mono` will be return, subscribing to this `Publisher` one can react 187 | on a successfully finished operation or handle issues that might happen. On the other hand 188 | cancelling this `Mono`, the underlying connecting operation will be aborted. If one do not need to interact with the 189 | `Mono`, there is `TcpServer.bindNow(Duration)` which is a convenient method for binding the server and obtaining 190 | the `DisposableServer`. 191 | `DisposableServer` holds contextual information for the underlying server. 192 | Disposing the resources can be done via `DisposableServer.dispose()` or `DisposableServer.disposeNow()`. 193 | 194 | === Enabling SSL support for TCP server 195 | `TcpServer` provides several convenient methods for configuring SSL: 196 | 197 | * `TcpServer.secure(SslContext)` where SslContext is already configured 198 | * `TcpServer.secure(Consumer)` where the SSL configuration customization 199 | can be done via the passed builder. 200 | 201 | === Add TCP server IO handler that will send a file 202 | `TcpServer.handle(BiFunction>)` should be used if one wants to attach IO 203 | handler that will process the incoming messages and will eventually send messages as a reply. 204 | `NettyInbound` is used to receive bytes from the peer where `NettyInbound.receiveObject()` returns the pure inbound 205 | `Flux`, while `NettyInbound.receive()` returns `ByteBufFlux` which provides an extra API to handle the incoming traffic. 206 | `NettyOutbound` is used to send bytes to the peer, listen for any error returned by the write operation 207 | and close on terminal signal (complete|error). If more than one `Publisher` is attached 208 | (multiple calls to `NettyOutbound.send*` methods), completion occurs when all publishers complete. 209 | The `Publisher` that has to be returned as a result represents the sequence of the operations that will be 210 | applied for the incoming and outgoing traffic. 211 | For example if one wants to send a file to the client where the file name is received as an incoming package, 212 | the snippet bellow can be used: 213 | 214 | [source, java] 215 | ---- 216 | .handle((in, out) -> 217 | in.receive() 218 | .asString() 219 | .flatMap(s -> { 220 | try { 221 | Path file = Paths.get(getClass().getResource(s).toURI()); 222 | return out.sendFile(file) 223 | .then(); 224 | } catch (URISyntaxException e) { 225 | return Mono.error(e); 226 | } 227 | })) 228 | ---- 229 | 230 | === Creating TCP client 231 | `TcpClient` allows to build, configure and materialize a `TCP` client. 232 | Invoking `TcpClient.create()` one can prepare the `TCP` client for configuration. Having already a `TcpClient` 233 | instance, one can start configuring the host, port, the IO handler etc. 234 | For configuration purposes, the same immutable builder pattern is used as in `UdpServer`. 235 | 236 | When finished with the client configuration, invoking `TcpClient.connect()`, one will connect the client 237 | and `Mono` will be return, subscribing to this `Publisher` one can react 238 | on a successfully finished operation or handle issues that might happen. On the other hand 239 | cancelling this `Mono`, the underlying connecting operation will be aborted. If one do not need to interact with the 240 | `Mono`, there is `TcpClient.connectNow(Duration)` which is a convenient method for connecting the client and obtaining 241 | the `Connection`. 242 | As already described in the `UDP` server section, disposing the resources can be done via `Connection.dispose()` 243 | or `Connection.disposeNow()`. 244 | 245 | === Enabling SSL support for TCP client 246 | `TcpClient` provides several convenient methods for configuring SSL. 247 | When one wants to use the default SSL configuration provided by Reactor Netty `TcpClient.secure()` can be used. 248 | If additional configuration is necessary then one of the following methods can be used: 249 | 250 | * `TcpClient.secure(SslContext)` where SslContext is already configured 251 | * `TcpClient.secure(Consumer)` where the SSL configuration customization 252 | can be done via the passed builder. 253 | 254 | === Add TCP client IO handler 255 | `TcpClient.handle(BiFunction>)` should be used if one wants to attach IO 256 | handler that will process the incoming messages and will eventually send messages as reply. 257 | Here as a convenience `NettyOutbound.send*` (e.g. `NettyOutbound.sendString`) methods can be used instead of 258 | `NettyOutbound.sendObject`. The same is also for using `NettyInbound.receive()` instead of 259 | `NettyInbound.receiveObject()`. 260 | 261 | == HTTP server and client 262 | === Creating HTTP server 263 | `HttpServer` allows to build, configure and materialize a `HTTP` server. 264 | Invoking `HttpServer.create()` one can prepare the `HTTP` server for configuration. Having already a `HttpServer` 265 | instance, one can start configuring the host, port, the IO handler, compression etc. 266 | For configuration purposes, the same immutable builder pattern is used as in `UdpServer`. 267 | 268 | When finished with the server configuration, invoking `HttpServer.bind`, one will bind the server 269 | and `Mono` will be return, subscribing to this `Publisher` one can react 270 | on a successfully finished operation or handle issues that might happen. On the other hand 271 | cancelling this `Mono`, the underlying connecting operation will be aborted. If one do not need to interact with the 272 | `Mono`, there is `HttpServer.bindNow(Duration)` which is a convenient method for binding the server and obtaining 273 | the `DisposableServer`. 274 | Disposing the resources can be done via `DisposableServer.dispose()` or `DisposableServer.disposeNow()`. 275 | 276 | === Defining routes for the HTTP server 277 | In `HttpServer` one can handle the incoming requests and outgoing responses using 278 | `HttpServer.handle(BiFunction>)` which is similar to the 279 | mechanism that was already described for `UdpServer`/`TcpServer`. However there is also a possibility to specify 280 | concrete routes and HTTP methods that the server will respond. This can be done using 281 | `HttpServer.route(Consumer)`. Using `HttpServerRoutes` one can specify the HTTP method, paths etc. 282 | For example the snippet below specifies that the server will respond only on `POST` method, where the path starts with 283 | `/test` and has a path parameter. 284 | 285 | [source, java] 286 | ---- 287 | .route(routes -> 288 | routes.post("/test/{param}", (req, res) -> 289 | res.sendString(req.receive() 290 | .asString() 291 | .map(s -> s + ' ' + req.param("param") + '!')))) 292 | ---- 293 | 294 | `HttpServerRequest` provides API for accessing http request attributes as method, path, headers, path parameters etc. 295 | as well as to receive the request body. 296 | `HttpServerResponse` provides API for accessing http response attributes as status code, headers, compression etc. 297 | as well as to send the response body. 298 | 299 | === Creating HTTP client 300 | `HttpClient` allows to build, configure and materialize a `HTTP` client. 301 | Invoking `HttpClient.create()` one can prepare the `HTTP` client for configuration. Having already a `HttpClient` 302 | instance, one can start configuring the host, port, headers, compression etc. 303 | For configuration purposes, the same immutable builder pattern is used as in `UdpServer`. 304 | 305 | When finished with the client configuration, invoking `HttpClient.get|post|...` methods, one will receive 306 | `HttpClient.RequestSender` and will be able start configuring the `HTTP` request such as the uri and the request body. 307 | `HttpClient.RequestSender.send*` will end the HTTP request's configuration and one can start discribing the actions 308 | on the `HTTP` response when it is received on the returned `HttpClient.ResponseReceiver`, the response body can be obtained via the provided 309 | `HttpClient.ResponseReceiver.response*` methods. As `HttpClient.ResponseReceiver` API always returns `Publisher`, 310 | the request and response executions are always deferred to the moment when there is a `Subscriber` 311 | that subscribes to the defined sequence. For example in the snippet below `block()` will subscribe to the defined 312 | sequence and in fact will trigger the execution. 313 | 314 | In the snippet below can be used to send POST request with a body and received the answer from the server: 315 | 316 | [source, java] 317 | ---- 318 | HttpClient.create() // Prepares a HTTP client for configuration. 319 | .port(server.port()) // Obtain the server's port and provide it as a port to which this 320 | // client should connect. 321 | .wiretap(true) // Applies a wire logger configuration. 322 | .headers(h -> h.add("Content-Type", "text/plain")) // Adds headers to the HTTP request. 323 | .post() // Specifies that POST method will be used. 324 | .uri("/test/World") // Specifies the path. 325 | .send(ByteBufFlux.fromString(Flux.just("Hello"))) // Sends the request body. 326 | .responseContent() // Receives the response body. 327 | .aggregate() 328 | .asString() 329 | .block(); 330 | ---- 331 | -------------------------------------------------------------------------------- /docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | Reactor Netty Workshop 10 | 11 | 439 | 440 | 441 | 442 | 443 | 484 |
485 |
486 |
487 |
488 |

This repository hosts a complete workshop on Reactor Netty.

489 |
490 |
491 |

When finishing the workshop one will know how to create and utilize:

492 |
493 |
494 |
    495 |
  • 496 |

    UDP server and client

    497 |
  • 498 |
  • 499 |

    TCP server and client

    500 |
  • 501 |
  • 502 |

    HTTP server and client

    503 |
  • 504 |
505 |
506 |
507 |

Reference documentation can be useful while creating those servers and clients:

508 |
509 |
510 | 521 |
522 |
523 |
524 |
525 |

Prerequisites

526 |
527 |
528 |
    529 |
  • 530 |

    Java 8

    531 |
  • 532 |
  • 533 |

    Java IDE installed with Maven support

    534 |
  • 535 |
536 |
537 |
538 |
539 |
540 |

How to start

541 |
542 |
543 |
    544 |
  • 545 |

    Clone/fork this repository https://github.com/violetagg/reactor-netty-workshop

    546 |
  • 547 |
  • 548 |

    Import the project as Maven one in your IDE

    549 |
  • 550 |
  • 551 |

    Make sure that the language level is set to Java 8 in your IDE project settings

    552 |
  • 553 |
  • 554 |

    Follow this script to create HTTP/TCP/UDP server and client

    555 |
  • 556 |
  • 557 |

    Fix the TODO one by one in the tests under io.spring.workshop.reactornetty 558 | package in order to make the unit tests green

    559 |
  • 560 |
  • 561 |

    The solution is available in the complete branch for comparison. Each step of this workshop 562 | has its companion commit in the git history with a detailed commit message.

    563 |
  • 564 |
565 |
566 |
567 |
568 |
569 |

UDP server and client

570 |
571 |
572 |

If one wants to utilize the UDP protocol one will need to create a UDP servers that can send packages 573 | to each other or even UDP clients that can connect to specific UDP servers. 574 | Reactor Netty provides easy to use and configure UdpServer and UdpClient, they hide most of the 575 | Netty functionality that is needed in order to create UDP server and client, and in addition add 576 | Reactive Streams backpressure.

577 |
578 |
579 |

Creating UDP server

580 |
581 |

UdpServer allows to build, configure and materialize a UDP server. 582 | Invoking UdpServer.create() one can prepare the UDP server for configuration. Having already a UdpServer 583 | instance, one can start configuring the host, port, the IO handler etc. 584 | For configuration purposes, an immutable builder pattern is used. 585 | In the example below the UDP server will be bound on port 8080 and will not use a random port.

586 |
587 |
588 |
589 |
UdpServer.create()  // Prepares a UDP server for configuration.
590 |          .port(0)   // Configures the port number as zero, this will let the system
591 |                     // pick up an ephemeral port when binding the server.
592 |          .port(8080)// Configures the port number as 8080.
593 |          .bind()    // Binds the UDP server and returns a Mono<Connection>.
594 |          .block();  // Blocks and waits the server to finish initialising.
595 |
596 |
597 |
598 |

When finished with the server configuration, invoking UdpServer.bind(), one will bind the server 599 | and Mono<Connection> will be return, subscribing to this Publisher one can react 600 | on a successfully finished operation or handle issues that might happen. On the other hand 601 | cancelling this Mono, the underlying binding will be aborted. If one do not need to interact with the Mono, 602 | there is UdpServer.bindNow(Duration) which is a convenient method for binding the server and obtaining the 603 | Connection. 604 | The Connection that is emitted as a result of a successfully bound server, holds contextual information 605 | for the underlying channel and provides a non-blocking resource disposing API. 606 | Disposing resource is very important so once the server is not necessary anymore, it must be disposed 607 | by the user via Connection.dispose() or Connection.disposeNow(). The difference between these two methods is 608 | that the second one will release the resources and close the underlying channel in a blocking fashion.

609 |
610 |
611 |
612 |

Configuring UDP server

613 |
614 |

Configuring the Wire Logger

615 |
616 |

There are use case when one wants to enable a wire logger in order to understand what’s wrong with the server. 617 | For that purposes UdpServer.wiretap can be used and this will use reactor.netty.udp.UdpServer category 618 | with DEBUG level. There are also UdpServer.wiretap(String) and UdpServer.wiretap(String, LogLevel) so that 619 | one can change the category and the log level.

620 |
621 |
622 |
623 |

Configuring the Event Loop Group

624 |
625 |

By default the UDP server will use Event Loop Group where the number of the worker threads will be 626 | the number of processors available to the runtime on init (but with a minimum value of 4). When 627 | one needs a different configuration, one of the LoopResource.create methods can be used in order to configure a new 628 | Event Loop Group. Once the Event Loop Group is configured, the new configuration can be provided using one of the 629 | UdpServer.runOn.

630 |
631 |
632 |
633 |
634 |

Add UDP server IO handler that will echo the received package

635 |
636 |

UdpServer.handle(BiFunction<UdpInbound, UdpOutbound, Publisher<Void>>) should be used if one wants to attach IO 637 | handler that will process the incoming packages and will eventually send packages as reply. 638 | UdpInbound is used to receive bytes from the peer where UdpInbound.receiveObject() returns the pure inbound 639 | Flux, while UdpInbound.receive() returns ByteBufFlux which provides an extra API to handle the incoming traffic. 640 | UdpOutbound is used to send bytes to the peer, listen for any error returned by the write operation 641 | and close on terminal signal (complete|error). If more than one Publisher is attached 642 | (multiple calls to UdpOutbound.send* methods), completion occurs when all publishers complete. 643 | The Publisher<Void> that has to be returned as a result represents the sequence of the operations that will be 644 | applied for the incoming and outgoing traffic. 645 | The packages that will be received and that will be send are handled by io.netty.channel.socket.DatagramPacket. 646 | For example if one wants to transform an incoming package and then to prepare a new one for sending, the snippet bellow 647 | can be used:

648 |
649 |
650 |
651 |
if (o instanceof DatagramPacket) {
652 |     // Incoming DatagramPacket
653 |     DatagramPacket p = (DatagramPacket) o;
654 |     ByteBuf buf1 = Unpooled.copiedBuffer("Hello ", CharsetUtil.UTF_8);
655 |     // Creates a new ByteBuf using the incoming DatagramPacket content.
656 |     ByteBuf buf2 = Unpooled.copiedBuffer(buf1, p.content()
657 |                                                 .retain());
658 |     // Creates a new DatagramPacket with the ByteBuf and the sender
659 |     // information from the incoming DatagramPacket.
660 |     return new DatagramPacket(buf2, p.sender());
661 | }
662 |
663 |
664 |
665 |
666 |

Creating UDP client

667 |
668 |

UdpClient allows to build, configure and materialize a UDP client. 669 | Invoking UdpClient.create() one can prepare the UDP client for configuration. Having already a UdpClient 670 | instance, one can start configuring the host, port, the IO handler etc. 671 | For configuration purposes, the same immutable builder pattern is used as in UdpServer.

672 |
673 |
674 |

When finished with the client configuration, invoking UdpClient.connect(), one will connect the client 675 | and Mono<Connection> will be return, subscribing to this Publisher one can react 676 | on a successfully finished operation or handle issues that might happen. On the other hand 677 | cancelling this Mono, the underlying connecting operation will be aborted. If one do not need to interact with the 678 | Mono, there is UdpClient.connectNow(Duration) which is a convenient method for connecting the client and obtaining 679 | the Connection. 680 | As already described in the UDP server section, disposing the resources can be done via Connection.dispose() 681 | or Connection.disposeNow().

682 |
683 |
684 |
685 |

Configuring UDP client

686 |
687 |

Configuring the Wire Logger

688 |
689 |

UdpClient.wiretap can be used for wire logging and this will use reactor.netty.udp.UdpClient category 690 | with DEBUG level. There are also UdpClient.wiretap(String) and UdpClient.wiretap(String, LogLevel) so that 691 | one can change the category and the log level.

692 |
693 |
694 |
695 |

Configuring the Event Loop Group

696 |
697 |

The default configuration for the Event Loop Group is the same as in UDP server. 698 | When one needs a different configuration, UdpClient.runOn methods can be used.

699 |
700 |
701 |
702 |
703 |

Add UDP client IO handler that will send a package and will react on an incoming packages

704 |
705 |

UdpClient.handle(BiFunction<UdpInbound, UdpOutbound, Publisher<Void>>) should be used if one wants to attach IO 706 | handler that will process the incoming packages and will eventually send packages as reply. 707 | Here as a convenience UdpOutbound.send* (e.g. UdpOutbound.sendString) methods can be used instead of 708 | UdpOutbound.sendObject as the client is connected to exactly one UDP server. The same is also for 709 | using UdpInbound.receive() instead of UdpInbound.receiveObject().

710 |
711 |
712 |
713 |

Utilize Mono<Connection>

714 |
715 |

In the section for the UDP server creation was described that as a result of UdpServer.bind one will 716 | receive Mono<Connection> which will emit (complete|error) signals. 717 | Utilizing this Mono one can send a datagram package (the snippet below) as soon as the UDP server is 718 | bound successfully.

719 |
720 |
721 |
722 |
DatagramChannel udp = DatagramChannel.open();
723 | udp.configureBlocking(true);
724 | udp.connect(new InetSocketAddress(server1.address().getPort()));
725 | 
726 | byte[] data = new byte[1024];
727 | new Random().nextBytes(data);
728 | for (int i = 0; i < 4; i++) {
729 |     udp.write(ByteBuffer.wrap(data));
730 | }
731 | 
732 | udp.close();
733 |
734 |
735 |
736 |
737 |
738 |
739 |

TCP server and client

740 |
741 |
742 |

If one wants to utilize the TCP protocol one will need to create a TCP servers that can send packages 743 | to the connected clients or TCP clients that can connect to specific TCP servers. 744 | Reactor Netty provides easy to use and configure TcpServer and TcpClient, they hide most of the 745 | Netty functionality that is needed in order to create with TCP server and client, and in addition add 746 | Reactive Streams backpressure.

747 |
748 |
749 |

Creating TCP server

750 |
751 |

TcpServer allows to build, configure and materialize a TCP server. 752 | Invoking TcpServer.create() one can prepare the TCP server for configuration. Having already a TcpServer 753 | instance, one can start configuring the host, port, the IO handler etc. 754 | For configuration purposes, the same immutable builder pattern is used as in UdpServer.

755 |
756 |
757 |

When finished with the server configuration, invoking TcpServer.bind, one will bind the server 758 | and Mono<DisposableServer> will be return, subscribing to this Publisher one can react 759 | on a successfully finished operation or handle issues that might happen. On the other hand 760 | cancelling this Mono, the underlying connecting operation will be aborted. If one do not need to interact with the 761 | Mono, there is TcpServer.bindNow(Duration) which is a convenient method for binding the server and obtaining 762 | the DisposableServer. 763 | DisposableServer holds contextual information for the underlying server. 764 | Disposing the resources can be done via DisposableServer.dispose() or DisposableServer.disposeNow().

765 |
766 |
767 |
768 |

Enabling SSL support for TCP server

769 |
770 |

TcpServer provides several convenient methods for configuring SSL:

771 |
772 |
773 |
    774 |
  • 775 |

    TcpServer.secure(SslContext) where SslContext is already configured

    776 |
  • 777 |
  • 778 |

    TcpServer.secure(Consumer<? super SslProvider.SslContextSpec>) where the SSL configuration customization 779 | can be done via the passed builder.

    780 |
  • 781 |
782 |
783 |
784 |
785 |

Add TCP server IO handler that will send a file

786 |
787 |

TcpServer.handle(BiFunction<NettyInbound, NettyOutbound, Publisher<Void>>) should be used if one wants to attach IO 788 | handler that will process the incoming messages and will eventually send messages as a reply. 789 | NettyInbound is used to receive bytes from the peer where NettyInbound.receiveObject() returns the pure inbound 790 | Flux, while NettyInbound.receive() returns ByteBufFlux which provides an extra API to handle the incoming traffic. 791 | NettyOutbound is used to send bytes to the peer, listen for any error returned by the write operation 792 | and close on terminal signal (complete|error). If more than one Publisher is attached 793 | (multiple calls to NettyOutbound.send* methods), completion occurs when all publishers complete. 794 | The Publisher<Void> that has to be returned as a result represents the sequence of the operations that will be 795 | applied for the incoming and outgoing traffic. 796 | For example if one wants to send a file to the client where the file name is received as an incoming package, 797 | the snippet bellow can be used:

798 |
799 |
800 |
801 |
.handle((in, out) ->
802 |         in.receive()
803 |           .asString()
804 |           .flatMap(s -> {
805 |               try {
806 |                   Path file = Paths.get(getClass().getResource(s).toURI());
807 |                   return out.sendFile(file)
808 |                             .then();
809 |               } catch (URISyntaxException e) {
810 |                   return Mono.error(e);
811 |               }
812 |           }))
813 |
814 |
815 |
816 |
817 |

Creating TCP client

818 |
819 |

TcpClient allows to build, configure and materialize a TCP client. 820 | Invoking TcpClient.create() one can prepare the TCP client for configuration. Having already a TcpClient 821 | instance, one can start configuring the host, port, the IO handler etc. 822 | For configuration purposes, the same immutable builder pattern is used as in UdpServer.

823 |
824 |
825 |

When finished with the client configuration, invoking TcpClient.connect(), one will connect the client 826 | and Mono<Connection> will be return, subscribing to this Publisher one can react 827 | on a successfully finished operation or handle issues that might happen. On the other hand 828 | cancelling this Mono, the underlying connecting operation will be aborted. If one do not need to interact with the 829 | Mono, there is TcpClient.connectNow(Duration) which is a convenient method for connecting the client and obtaining 830 | the Connection. 831 | As already described in the UDP server section, disposing the resources can be done via Connection.dispose() 832 | or Connection.disposeNow().

833 |
834 |
835 |
836 |

Enabling SSL support for TCP client

837 |
838 |

TcpClient provides several convenient methods for configuring SSL. 839 | When one wants to use the default SSL configuration provided by Reactor Netty TcpClient.secure() can be used. 840 | If additional configuration is necessary then one of the following methods can be used:

841 |
842 |
843 |
    844 |
  • 845 |

    TcpClient.secure(SslContext) where SslContext is already configured

    846 |
  • 847 |
  • 848 |

    TcpClient.secure(Consumer<? super SslProvider.SslContextSpec>) where the SSL configuration customization 849 | can be done via the passed builder.

    850 |
  • 851 |
852 |
853 |
854 |
855 |

Add TCP client IO handler

856 |
857 |

TcpClient.handle(BiFunction<NettyInbound, NettyOutbound, Publisher<Void>>) should be used if one wants to attach IO 858 | handler that will process the incoming messages and will eventually send messages as reply. 859 | Here as a convenience NettyOutbound.send* (e.g. NettyOutbound.sendString) methods can be used instead of 860 | NettyOutbound.sendObject. The same is also for using NettyInbound.receive() instead of 861 | NettyInbound.receiveObject().

862 |
863 |
864 |
865 |
866 |
867 |

HTTP server and client

868 |
869 |
870 |

Creating HTTP server

871 |
872 |

HttpServer allows to build, configure and materialize a HTTP server. 873 | Invoking HttpServer.create() one can prepare the HTTP server for configuration. Having already a HttpServer 874 | instance, one can start configuring the host, port, the IO handler, compression etc. 875 | For configuration purposes, the same immutable builder pattern is used as in UdpServer.

876 |
877 |
878 |

When finished with the server configuration, invoking HttpServer.bind, one will bind the server 879 | and Mono<DisposableServer> will be return, subscribing to this Publisher one can react 880 | on a successfully finished operation or handle issues that might happen. On the other hand 881 | cancelling this Mono, the underlying connecting operation will be aborted. If one do not need to interact with the 882 | Mono, there is HttpServer.bindNow(Duration) which is a convenient method for binding the server and obtaining 883 | the DisposableServer. 884 | Disposing the resources can be done via DisposableServer.dispose() or DisposableServer.disposeNow().

885 |
886 |
887 |
888 |

Defining routes for the HTTP server

889 |
890 |

In HttpServer one can handle the incoming requests and outgoing responses using 891 | HttpServer.handle(BiFunction<HttpServerRequest, HttpServerResponse, Publisher<Void>>) which is similar to the 892 | mechanism that was already described for UdpServer/TcpServer. However there is also a possibility to specify 893 | concrete routes and HTTP methods that the server will respond. This can be done using 894 | HttpServer.route(Consumer<HttpServerRoutes>). Using HttpServerRoutes one can specify the HTTP method, paths etc. 895 | For example the snippet below specifies that the server will respond only on POST method, where the path starts with 896 | /test and has a path parameter.

897 |
898 |
899 |
900 |
.route(routes ->
901 |         routes.post("/test/{param}", (req, res) ->
902 |                 res.sendString(req.receive()
903 |                                   .asString()
904 |                                   .map(s -> s + ' ' + req.param("param") + '!'))))
905 |
906 |
907 |
908 |

HttpServerRequest provides API for accessing http request attributes as method, path, headers, path parameters etc. 909 | as well as to receive the request body. 910 | HttpServerResponse provides API for accessing http response attributes as status code, headers, compression etc. 911 | as well as to send the response body.

912 |
913 |
914 |
915 |

Creating HTTP client

916 |
917 |

HttpClient allows to build, configure and materialize a HTTP client. 918 | Invoking HttpClient.create() one can prepare the HTTP client for configuration. Having already a HttpClient 919 | instance, one can start configuring the host, port, headers, compression etc. 920 | For configuration purposes, the same immutable builder pattern is used as in UdpServer.

921 |
922 |
923 |

When finished with the client configuration, invoking HttpClient.get|post|…​ methods, one will receive 924 | HttpClient.RequestSender and will be able start configuring the HTTP request such as the uri and the request body. 925 | HttpClient.RequestSender.send* will end the HTTP request’s configuration and one can start discribing the actions 926 | on the HTTP response when it is received on the returned HttpClient.ResponseReceiver, the response body can be obtained via the provided 927 | HttpClient.ResponseReceiver.response* methods. As HttpClient.ResponseReceiver API always returns Publisher, 928 | the request and response executions are always deferred to the moment when there is a Subscriber 929 | that subscribes to the defined sequence. For example in the snippet below block() will subscribe to the defined 930 | sequence and in fact will trigger the execution.

931 |
932 |
933 |

In the snippet below can be used to send POST request with a body and received the answer from the server:

934 |
935 |
936 |
937 |
HttpClient.create()             // Prepares a HTTP client for configuration.
938 |           .port(server.port())  // Obtain the server's port and provide it as a port to which this
939 |                                 // client should connect.
940 |           .wiretap(true)        // Applies a wire logger configuration.
941 |           .headers(h -> h.add("Content-Type", "text/plain")) // Adds headers to the HTTP request.
942 |           .post()              // Specifies that POST method will be used.
943 |           .uri("/test/World")  // Specifies the path.
944 |           .send(ByteBufFlux.fromString(Flux.just("Hello")))  // Sends the request body.
945 |           .responseContent()   // Receives the response body.
946 |           .aggregate()
947 |           .asString()
948 |           .block();
949 |
950 |
951 |
952 |
953 |
954 |
955 | 960 | 961 | 962 | --------------------------------------------------------------------------------