Advertisement
Guest User

Untitled

a guest
Sep 16th, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. use std::time::{Instant, Duration};
  2. use tokio::{
  3. net::{TcpListener, TcpStream},
  4. timer::{Delay, Interval},
  5. runtime::Runtime,
  6. };
  7. use tokio_io::AsyncRead;
  8.  
  9. use futures::{
  10. prelude::*,
  11. sync::oneshot,
  12. };
  13.  
  14. fn handle_client(mut client: TcpStream) -> impl Future<Item = (), Error = ()> {
  15. let mut buf = Vec::with_capacity(32);
  16. while let Ok(Async::Ready(_len)) = client.read_buf(&mut buf) {
  17. println!("Handling client!");
  18. }
  19. Ok(()).into_future()
  20.  
  21. }
  22.  
  23. fn dummy_service() -> impl Future<Item = (), Error = ()> {
  24. // dummy service that finishes after 1 second
  25. Delay::new(Instant::now() + Duration::from_secs(1))
  26. .map_err(drop)
  27. }
  28.  
  29. fn server() -> impl Future<Item = (), Error = ()> {
  30. let addr = "127.0.0.1:1337".parse().unwrap();
  31.  
  32. let listener = TcpListener::bind(&addr)
  33. .expect("Failed to bind");
  34.  
  35. let accept_loop = listener.incoming()
  36. .for_each(|client| {
  37. tokio::spawn(handle_client(client));
  38. Ok(())
  39. })
  40. .map_err(drop);
  41.  
  42. accept_loop
  43. }
  44.  
  45. fn clients() -> impl Future<Item = (), Error = ()> {
  46. let addr = "127.0.0.1:1337".parse().unwrap();
  47.  
  48. // creates a client every 100ms
  49. Interval::new_interval(Duration::from_millis(100))
  50. .map_err(drop)
  51. .for_each(move |_| {
  52. TcpStream::connect(&addr)
  53. .map(drop)
  54. .map_err(drop)
  55. })
  56.  
  57. }
  58.  
  59. fn main() {
  60. let mut rt = Runtime::new().unwrap();
  61.  
  62. rt.spawn(clients());
  63.  
  64. let (tx, rx) = oneshot::channel();
  65.  
  66. let service = dummy_service()
  67. .and_then(|_| tx.send(()));
  68.  
  69. rt.spawn(service);
  70.  
  71. let server_with_shutdown = server()
  72. .select(rx.map_err(drop))
  73. .map(drop)
  74. .map_err(drop);
  75.  
  76. let _ = rt.block_on(server_with_shutdown);
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement