异步 TCP、UDP 及 HTTP
谁都不会比光的速度还要快,唯有坏消息例外,它们遵循自己的一套规律。
道格拉斯∙诺尔∙亚当斯
《基本无害》(1992)
先来一些网络方面的 Java 8 代码
import reactor.io.net.NetStreams;
import reactor.io.net.tcp.TcpServer;
import reactor.io.net.tcp.TcpClient;
//...
CountDownLatch latch = new CountDownLatch(10);
TcpServer<Buffer, Buffer> server = NetStreams.tcpServer(port);
TcpClient<Buffer, Buffer> client = NetStreams.tcpClient("localhost", port);
final JsonCodec<Pojo, Pojo> codec = new JsonCodec<Pojo, Pojo>(Pojo.class);
//the client/server are prepared
server.start( input ->
//for each connection echo any incoming data
//return the write confirm publisher from writeWith
// >>> close when the write confirm completed
input.writeWith(
//read incoming data
input
.decode(codec) //transform Buffer into Pojo
.log("serve")
.map(codec) //transform Pojo into Buffer
.capacity(5l) //auto-flush every 5 elements
)
).await();
client.start( input -> {
//read 10 replies and close
input
.take(10)
.decode(codec)
.log("receive")
.consume( data -> latch.countDown() );
//write data
input.writeWith(
Streams.range(1, 10)
.map( it -> new Pojo("test" + it) )
.log("send")
.map(codec)
);
//keep-alive, until 10 data have been read
return Streams.never();
}).await();
latch.await(10, TimeUnit.SECONDS);
client.shutdown().await();
server.shutdown().await();