mod.rs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. use std::path::PathBuf;
  2. use anyhow::Result;
  3. use tokio::{
  4. io::{self, AsyncReadExt, AsyncWriteExt},
  5. net::{TcpListener, TcpStream, ToSocketAddrs},
  6. sync::broadcast,
  7. };
  8. pub const PING: &str = "ping";
  9. pub const PONG: &str = "pong";
  10. pub async fn run_rathole_server(
  11. config_path: &str,
  12. shutdown_rx: broadcast::Receiver<bool>,
  13. ) -> Result<()> {
  14. let cli = rathole::Cli {
  15. config_path: PathBuf::from(config_path),
  16. server: true,
  17. client: false,
  18. };
  19. rathole::run(&cli, shutdown_rx).await
  20. }
  21. pub async fn run_rathole_client(
  22. config_path: &str,
  23. shutdown_rx: broadcast::Receiver<bool>,
  24. ) -> Result<()> {
  25. let cli = rathole::Cli {
  26. config_path: PathBuf::from(config_path),
  27. server: false,
  28. client: true,
  29. };
  30. rathole::run(&cli, shutdown_rx).await
  31. }
  32. pub async fn echo_server<A: ToSocketAddrs>(addr: A) -> Result<()> {
  33. let l = TcpListener::bind(addr).await?;
  34. loop {
  35. let (conn, _addr) = l.accept().await?;
  36. tokio::spawn(async move {
  37. let _ = echo(conn).await;
  38. });
  39. }
  40. }
  41. pub async fn pingpong_server<A: ToSocketAddrs>(addr: A) -> Result<()> {
  42. let l = TcpListener::bind(addr).await?;
  43. loop {
  44. let (conn, _addr) = l.accept().await?;
  45. tokio::spawn(async move {
  46. let _ = pingpong(conn).await;
  47. });
  48. }
  49. }
  50. async fn echo(conn: TcpStream) -> Result<()> {
  51. let (mut rd, mut wr) = conn.into_split();
  52. io::copy(&mut rd, &mut wr).await?;
  53. Ok(())
  54. }
  55. async fn pingpong(mut conn: TcpStream) -> Result<()> {
  56. let mut buf = [0u8; PING.len()];
  57. while conn.read_exact(&mut buf).await? != 0 {
  58. assert_eq!(buf, PING.as_bytes());
  59. conn.write_all(PONG.as_bytes()).await?;
  60. }
  61. Ok(())
  62. }