异步 TCP、UDP 及 HTTP

谁都不会比光的速度还要快,唯有坏消息例外,它们遵循自己的一套规律。

道格拉斯∙诺尔∙亚当斯
《基本无害》(1992)

先来一些网络方面的 Java 8 代码

  1. import reactor.io.net.NetStreams;
  2. import reactor.io.net.tcp.TcpServer;
  3. import reactor.io.net.tcp.TcpClient;
  4. //...
  5. CountDownLatch latch = new CountDownLatch(10);
  6. TcpServer<Buffer, Buffer> server = NetStreams.tcpServer(port);
  7. TcpClient<Buffer, Buffer> client = NetStreams.tcpClient("localhost", port);
  8. final JsonCodec<Pojo, Pojo> codec = new JsonCodec<Pojo, Pojo>(Pojo.class);
  9. //the client/server are prepared
  10. server.start( input ->
  11. //for each connection echo any incoming data
  12. //return the write confirm publisher from writeWith
  13. // >>> close when the write confirm completed
  14. input.writeWith(
  15. //read incoming data
  16. input
  17. .decode(codec) //transform Buffer into Pojo
  18. .log("serve")
  19. .map(codec) //transform Pojo into Buffer
  20. .capacity(5l) //auto-flush every 5 elements
  21. )
  22. ).await();
  23. client.start( input -> {
  24. //read 10 replies and close
  25. input
  26. .take(10)
  27. .decode(codec)
  28. .log("receive")
  29. .consume( data -> latch.countDown() );
  30. //write data
  31. input.writeWith(
  32. Streams.range(1, 10)
  33. .map( it -> new Pojo("test" + it) )
  34. .log("send")
  35. .map(codec)
  36. );
  37. //keep-alive, until 10 data have been read
  38. return Streams.never();
  39. }).await();
  40. latch.await(10, TimeUnit.SECONDS);
  41. client.shutdown().await();
  42. server.shutdown().await();