Skip to content

Instantly share code, notes, and snippets.

@simbo1905
Created November 3, 2019 22:10
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save simbo1905/213e1bf966dc80e04349977a1bcb7b00 to your computer and use it in GitHub Desktop.
how to write an echo server with reactor-netty 0.9.1.RELEASE
package demo;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;
import reactor.netty.DisposableServer;
import reactor.netty.tcp.TcpServer;
public class TrexTcpServer {
public static void main(String[] args) {
final TcpServer server =
TcpServer.create()
.port(8080).wiretap(true);
DisposableServer connectedServer = server.handle((in, out) ->
in.receive()
.asString()
.map(s -> {
System.out.println(s);
ByteBuf buf1 = Unpooled.copiedBuffer("echo: "+s, CharsetUtil.UTF_8);
return buf1;
})
.flatMap(out::sendObject)
.log("tcp-server")).bindNow();
connectedServer.onDispose()
.block();
}
}
package demo;
import io.netty.handler.timeout.ReadTimeoutHandler;
import reactor.core.publisher.Mono;
import reactor.netty.Connection;
import reactor.netty.tcp.TcpClient;
import java.util.concurrent.TimeUnit;
public class TrexTestClient {
public static void print(String s) {
System.out.println(s);
}
public static void main(String[] args) {
Connection connection =
TcpClient.create()
.host("127.0.0.1")
.port(8080)
.doOnConnected(conn ->
conn.addHandler(new ReadTimeoutHandler(10, TimeUnit.SECONDS)))
.handle((in, out) ->
out.sendString(Mono.just("/index.html"))
.then(in.receive()
.asByteArray()
.doOnNext(actualBytes -> {
System.out.println(new String(actualBytes));
})
.log("tcp-client")
.then()))
.connectNow();
connection.onDispose()
.block();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment