#listen #server #networking #server-connection #protwrap

lstnconn

Simple listener and connections abstraction built on protwrap

1 unstable release

0.1.1 May 31, 2024
0.1.0 May 31, 2024

#13 in #listen

0BSD license

10KB
140 lines

lstnconn

Abstraction around network listeners that spawn connections.


lib.rs:

use lstnconn::{
  Handler, ListenConnMgr, async_trait, Stream, ConnInfo, Handle,
  KillSwitch, Listener
};

// Handler used to process connections
struct MyHandler { }

// Per-connection data type
#[derive(Clone)]
struct ConnectData { }

#[async_trait]
impl Handler for MyHandler {
  type ConnCtx = ConnectData;
  async fn connected(&self, ci: ConnInfo) -> Handle<Self::ConnCtx> {
    // A connection has been established, tell listener to spawn a new task
    // for running connection handler on.
    Handle::Task(ConnectData {})
  }
  async fn run(&self, conn: Stream, cctx: &mut Self::ConnCtx) {
    // .. process the server connection here ..
  }
  async fn disconnected(&self, cctx: Self::ConnCtx) {
    // .. a connection has terminated ..
  }
}

let handler = MyHandler { };
let lcm = ListenConnMgr::new(handler);

// Create a KillSwitch for terminating the listener loop
let ks = KillSwitch::new();

// Create a localhost Listener using a system-assigned port
let listener = Listener::tcp("127.0.0.1:0").unwrap();

// Run the listen/connection loop in a background task
task::spawn(lcm.run(listener, ks));

Dependencies

~12–21MB
~381K SLoC