Skip to main content

Client

Struct Client 

Source
pub struct Client { /* private fields */ }
Expand description

Sans-IO Kermit client. See the crate documentation for the driver loop.

Implementations§

Source§

impl Client

Source

pub fn new(config: Config) -> Self

New idle client.

Examples found in repository?
examples/record.rs (line 63)
35fn main() -> Result<(), Box<dyn std::error::Error>> {
36    let args: Vec<String> = std::env::args().skip(1).collect();
37    let (addr, cmd_args) = match args.split_first() {
38        Some((addr, rest)) if !rest.is_empty() => (addr, rest),
39        _ => return Err(USAGE.into()),
40    };
41    let command = parse_command(cmd_args)?;
42    println!("# record {}", cmd_args.join(" "));
43
44    let mut stream = TcpStream::connect(addr)?;
45    let mut buf = [0u8; 1024];
46
47    // Drain stale input (the idle server's periodic NAKs) for 500 ms.
48    let drain_end = Instant::now() + Duration::from_millis(500);
49    loop {
50        let left = drain_end.saturating_duration_since(Instant::now());
51        if left.is_zero() {
52            break;
53        }
54        stream.set_read_timeout(Some(left.max(Duration::from_millis(1))))?;
55        match stream.read(&mut buf) {
56            Ok(0) => return Err("connection closed".into()),
57            Ok(n) => println!("# stale: {}", escape(&buf[..n])),
58            Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => break,
59            Err(e) => return Err(e.into()),
60        }
61    }
62
63    let mut client = Client::new(Config::default());
64    client.start(Instant::now(), command)?;
65    let mut outcome: Option<bool> = None;
66    loop {
67        let now = Instant::now();
68        while let Some(bytes) = client.poll_output(now) {
69            stream.write_all(&bytes)?;
70            println!("> {}", escape(&bytes));
71        }
72        while let Some(event) = client.poll_event() {
73            eprintln!("{event:?}");
74            match event {
75                Event::Done => outcome = Some(true),
76                Event::Error(_) => outcome = Some(false),
77                _ => {}
78            }
79        }
80        let wait = match (client.next_timeout(), outcome) {
81            (None, Some(_)) => break,
82            (Some(t), _) => t.saturating_duration_since(now),
83            (None, None) => Duration::from_millis(100),
84        };
85        stream.set_read_timeout(Some(wait.max(Duration::from_millis(10))))?;
86        match stream.read(&mut buf) {
87            Ok(0) => return Err("connection closed".into()),
88            Ok(n) => {
89                println!("< {}", escape(&buf[..n]));
90                client.handle_input(Instant::now(), &buf[..n]);
91            }
92            Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {
93                client.handle_timeout(Instant::now());
94            }
95            Err(e) => return Err(e.into()),
96        }
97    }
98    std::io::stdout().flush()?;
99    if outcome == Some(true) {
100        Ok(())
101    } else {
102        std::process::exit(1);
103    }
104}
Source

pub fn start( &mut self, now: Instant, command: Command, ) -> Result<(), StartError>

Begin a transaction. First packet is available from poll_output(now) immediately.

Starts from a clean slate: buffered input, output and events of the previous transaction that were not polled yet are dropped, and Client::peer_params is cleared. A linger after the previous transaction (Config::linger) ends.

Fails with StartError::Busy while a transaction is running and with StartError::TooLong if the encoded command data does not fit in one packet; the client is unchanged in both cases.

Examples found in repository?
examples/record.rs (line 64)
35fn main() -> Result<(), Box<dyn std::error::Error>> {
36    let args: Vec<String> = std::env::args().skip(1).collect();
37    let (addr, cmd_args) = match args.split_first() {
38        Some((addr, rest)) if !rest.is_empty() => (addr, rest),
39        _ => return Err(USAGE.into()),
40    };
41    let command = parse_command(cmd_args)?;
42    println!("# record {}", cmd_args.join(" "));
43
44    let mut stream = TcpStream::connect(addr)?;
45    let mut buf = [0u8; 1024];
46
47    // Drain stale input (the idle server's periodic NAKs) for 500 ms.
48    let drain_end = Instant::now() + Duration::from_millis(500);
49    loop {
50        let left = drain_end.saturating_duration_since(Instant::now());
51        if left.is_zero() {
52            break;
53        }
54        stream.set_read_timeout(Some(left.max(Duration::from_millis(1))))?;
55        match stream.read(&mut buf) {
56            Ok(0) => return Err("connection closed".into()),
57            Ok(n) => println!("# stale: {}", escape(&buf[..n])),
58            Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => break,
59            Err(e) => return Err(e.into()),
60        }
61    }
62
63    let mut client = Client::new(Config::default());
64    client.start(Instant::now(), command)?;
65    let mut outcome: Option<bool> = None;
66    loop {
67        let now = Instant::now();
68        while let Some(bytes) = client.poll_output(now) {
69            stream.write_all(&bytes)?;
70            println!("> {}", escape(&bytes));
71        }
72        while let Some(event) = client.poll_event() {
73            eprintln!("{event:?}");
74            match event {
75                Event::Done => outcome = Some(true),
76                Event::Error(_) => outcome = Some(false),
77                _ => {}
78            }
79        }
80        let wait = match (client.next_timeout(), outcome) {
81            (None, Some(_)) => break,
82            (Some(t), _) => t.saturating_duration_since(now),
83            (None, None) => Duration::from_millis(100),
84        };
85        stream.set_read_timeout(Some(wait.max(Duration::from_millis(10))))?;
86        match stream.read(&mut buf) {
87            Ok(0) => return Err("connection closed".into()),
88            Ok(n) => {
89                println!("< {}", escape(&buf[..n]));
90                client.handle_input(Instant::now(), &buf[..n]);
91            }
92            Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {
93                client.handle_timeout(Instant::now());
94            }
95            Err(e) => return Err(e.into()),
96        }
97    }
98    std::io::stdout().flush()?;
99    if outcome == Some(true) {
100        Ok(())
101    } else {
102        std::process::exit(1);
103    }
104}
Source

pub fn handle_input(&mut self, now: Instant, bytes: &[u8])

Feed bytes read from the link.

Examples found in repository?
examples/record.rs (line 90)
35fn main() -> Result<(), Box<dyn std::error::Error>> {
36    let args: Vec<String> = std::env::args().skip(1).collect();
37    let (addr, cmd_args) = match args.split_first() {
38        Some((addr, rest)) if !rest.is_empty() => (addr, rest),
39        _ => return Err(USAGE.into()),
40    };
41    let command = parse_command(cmd_args)?;
42    println!("# record {}", cmd_args.join(" "));
43
44    let mut stream = TcpStream::connect(addr)?;
45    let mut buf = [0u8; 1024];
46
47    // Drain stale input (the idle server's periodic NAKs) for 500 ms.
48    let drain_end = Instant::now() + Duration::from_millis(500);
49    loop {
50        let left = drain_end.saturating_duration_since(Instant::now());
51        if left.is_zero() {
52            break;
53        }
54        stream.set_read_timeout(Some(left.max(Duration::from_millis(1))))?;
55        match stream.read(&mut buf) {
56            Ok(0) => return Err("connection closed".into()),
57            Ok(n) => println!("# stale: {}", escape(&buf[..n])),
58            Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => break,
59            Err(e) => return Err(e.into()),
60        }
61    }
62
63    let mut client = Client::new(Config::default());
64    client.start(Instant::now(), command)?;
65    let mut outcome: Option<bool> = None;
66    loop {
67        let now = Instant::now();
68        while let Some(bytes) = client.poll_output(now) {
69            stream.write_all(&bytes)?;
70            println!("> {}", escape(&bytes));
71        }
72        while let Some(event) = client.poll_event() {
73            eprintln!("{event:?}");
74            match event {
75                Event::Done => outcome = Some(true),
76                Event::Error(_) => outcome = Some(false),
77                _ => {}
78            }
79        }
80        let wait = match (client.next_timeout(), outcome) {
81            (None, Some(_)) => break,
82            (Some(t), _) => t.saturating_duration_since(now),
83            (None, None) => Duration::from_millis(100),
84        };
85        stream.set_read_timeout(Some(wait.max(Duration::from_millis(10))))?;
86        match stream.read(&mut buf) {
87            Ok(0) => return Err("connection closed".into()),
88            Ok(n) => {
89                println!("< {}", escape(&buf[..n]));
90                client.handle_input(Instant::now(), &buf[..n]);
91            }
92            Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {
93                client.handle_timeout(Instant::now());
94            }
95            Err(e) => return Err(e.into()),
96        }
97    }
98    std::io::stdout().flush()?;
99    if outcome == Some(true) {
100        Ok(())
101    } else {
102        std::process::exit(1);
103    }
104}
Source

pub fn handle_timeout(&mut self, now: Instant)

Call when the time from Client::next_timeout has passed.

Examples found in repository?
examples/record.rs (line 93)
35fn main() -> Result<(), Box<dyn std::error::Error>> {
36    let args: Vec<String> = std::env::args().skip(1).collect();
37    let (addr, cmd_args) = match args.split_first() {
38        Some((addr, rest)) if !rest.is_empty() => (addr, rest),
39        _ => return Err(USAGE.into()),
40    };
41    let command = parse_command(cmd_args)?;
42    println!("# record {}", cmd_args.join(" "));
43
44    let mut stream = TcpStream::connect(addr)?;
45    let mut buf = [0u8; 1024];
46
47    // Drain stale input (the idle server's periodic NAKs) for 500 ms.
48    let drain_end = Instant::now() + Duration::from_millis(500);
49    loop {
50        let left = drain_end.saturating_duration_since(Instant::now());
51        if left.is_zero() {
52            break;
53        }
54        stream.set_read_timeout(Some(left.max(Duration::from_millis(1))))?;
55        match stream.read(&mut buf) {
56            Ok(0) => return Err("connection closed".into()),
57            Ok(n) => println!("# stale: {}", escape(&buf[..n])),
58            Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => break,
59            Err(e) => return Err(e.into()),
60        }
61    }
62
63    let mut client = Client::new(Config::default());
64    client.start(Instant::now(), command)?;
65    let mut outcome: Option<bool> = None;
66    loop {
67        let now = Instant::now();
68        while let Some(bytes) = client.poll_output(now) {
69            stream.write_all(&bytes)?;
70            println!("> {}", escape(&bytes));
71        }
72        while let Some(event) = client.poll_event() {
73            eprintln!("{event:?}");
74            match event {
75                Event::Done => outcome = Some(true),
76                Event::Error(_) => outcome = Some(false),
77                _ => {}
78            }
79        }
80        let wait = match (client.next_timeout(), outcome) {
81            (None, Some(_)) => break,
82            (Some(t), _) => t.saturating_duration_since(now),
83            (None, None) => Duration::from_millis(100),
84        };
85        stream.set_read_timeout(Some(wait.max(Duration::from_millis(10))))?;
86        match stream.read(&mut buf) {
87            Ok(0) => return Err("connection closed".into()),
88            Ok(n) => {
89                println!("< {}", escape(&buf[..n]));
90                client.handle_input(Instant::now(), &buf[..n]);
91            }
92            Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {
93                client.handle_timeout(Instant::now());
94            }
95            Err(e) => return Err(e.into()),
96        }
97    }
98    std::io::stdout().flush()?;
99    if outcome == Some(true) {
100        Ok(())
101    } else {
102        std::process::exit(1);
103    }
104}
Source

pub fn poll_output(&mut self, now: Instant) -> Option<Vec<u8>>

Next bytes to write, written atomically (one packet incl. padding and EOL). None if nothing is due yet at now (packet_pause). Keep calling after Done/Error until None: the final ACK or an E packet may still be queued.

Examples found in repository?
examples/record.rs (line 68)
35fn main() -> Result<(), Box<dyn std::error::Error>> {
36    let args: Vec<String> = std::env::args().skip(1).collect();
37    let (addr, cmd_args) = match args.split_first() {
38        Some((addr, rest)) if !rest.is_empty() => (addr, rest),
39        _ => return Err(USAGE.into()),
40    };
41    let command = parse_command(cmd_args)?;
42    println!("# record {}", cmd_args.join(" "));
43
44    let mut stream = TcpStream::connect(addr)?;
45    let mut buf = [0u8; 1024];
46
47    // Drain stale input (the idle server's periodic NAKs) for 500 ms.
48    let drain_end = Instant::now() + Duration::from_millis(500);
49    loop {
50        let left = drain_end.saturating_duration_since(Instant::now());
51        if left.is_zero() {
52            break;
53        }
54        stream.set_read_timeout(Some(left.max(Duration::from_millis(1))))?;
55        match stream.read(&mut buf) {
56            Ok(0) => return Err("connection closed".into()),
57            Ok(n) => println!("# stale: {}", escape(&buf[..n])),
58            Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => break,
59            Err(e) => return Err(e.into()),
60        }
61    }
62
63    let mut client = Client::new(Config::default());
64    client.start(Instant::now(), command)?;
65    let mut outcome: Option<bool> = None;
66    loop {
67        let now = Instant::now();
68        while let Some(bytes) = client.poll_output(now) {
69            stream.write_all(&bytes)?;
70            println!("> {}", escape(&bytes));
71        }
72        while let Some(event) = client.poll_event() {
73            eprintln!("{event:?}");
74            match event {
75                Event::Done => outcome = Some(true),
76                Event::Error(_) => outcome = Some(false),
77                _ => {}
78            }
79        }
80        let wait = match (client.next_timeout(), outcome) {
81            (None, Some(_)) => break,
82            (Some(t), _) => t.saturating_duration_since(now),
83            (None, None) => Duration::from_millis(100),
84        };
85        stream.set_read_timeout(Some(wait.max(Duration::from_millis(10))))?;
86        match stream.read(&mut buf) {
87            Ok(0) => return Err("connection closed".into()),
88            Ok(n) => {
89                println!("< {}", escape(&buf[..n]));
90                client.handle_input(Instant::now(), &buf[..n]);
91            }
92            Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {
93                client.handle_timeout(Instant::now());
94            }
95            Err(e) => return Err(e.into()),
96        }
97    }
98    std::io::stdout().flush()?;
99    if outcome == Some(true) {
100        Ok(())
101    } else {
102        std::process::exit(1);
103    }
104}
Source

pub fn poll_event(&mut self) -> Option<Event>

Next event, in order.

Examples found in repository?
examples/record.rs (line 72)
35fn main() -> Result<(), Box<dyn std::error::Error>> {
36    let args: Vec<String> = std::env::args().skip(1).collect();
37    let (addr, cmd_args) = match args.split_first() {
38        Some((addr, rest)) if !rest.is_empty() => (addr, rest),
39        _ => return Err(USAGE.into()),
40    };
41    let command = parse_command(cmd_args)?;
42    println!("# record {}", cmd_args.join(" "));
43
44    let mut stream = TcpStream::connect(addr)?;
45    let mut buf = [0u8; 1024];
46
47    // Drain stale input (the idle server's periodic NAKs) for 500 ms.
48    let drain_end = Instant::now() + Duration::from_millis(500);
49    loop {
50        let left = drain_end.saturating_duration_since(Instant::now());
51        if left.is_zero() {
52            break;
53        }
54        stream.set_read_timeout(Some(left.max(Duration::from_millis(1))))?;
55        match stream.read(&mut buf) {
56            Ok(0) => return Err("connection closed".into()),
57            Ok(n) => println!("# stale: {}", escape(&buf[..n])),
58            Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => break,
59            Err(e) => return Err(e.into()),
60        }
61    }
62
63    let mut client = Client::new(Config::default());
64    client.start(Instant::now(), command)?;
65    let mut outcome: Option<bool> = None;
66    loop {
67        let now = Instant::now();
68        while let Some(bytes) = client.poll_output(now) {
69            stream.write_all(&bytes)?;
70            println!("> {}", escape(&bytes));
71        }
72        while let Some(event) = client.poll_event() {
73            eprintln!("{event:?}");
74            match event {
75                Event::Done => outcome = Some(true),
76                Event::Error(_) => outcome = Some(false),
77                _ => {}
78            }
79        }
80        let wait = match (client.next_timeout(), outcome) {
81            (None, Some(_)) => break,
82            (Some(t), _) => t.saturating_duration_since(now),
83            (None, None) => Duration::from_millis(100),
84        };
85        stream.set_read_timeout(Some(wait.max(Duration::from_millis(10))))?;
86        match stream.read(&mut buf) {
87            Ok(0) => return Err("connection closed".into()),
88            Ok(n) => {
89                println!("< {}", escape(&buf[..n]));
90                client.handle_input(Instant::now(), &buf[..n]);
91            }
92            Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {
93                client.handle_timeout(Instant::now());
94            }
95            Err(e) => return Err(e.into()),
96        }
97    }
98    std::io::stdout().flush()?;
99    if outcome == Some(true) {
100        Ok(())
101    } else {
102        std::process::exit(1);
103    }
104}
Source

pub fn next_timeout(&self) -> Option<Instant>

Earliest of: when a queued packet becomes due, the retransmit deadline.

Examples found in repository?
examples/record.rs (line 80)
35fn main() -> Result<(), Box<dyn std::error::Error>> {
36    let args: Vec<String> = std::env::args().skip(1).collect();
37    let (addr, cmd_args) = match args.split_first() {
38        Some((addr, rest)) if !rest.is_empty() => (addr, rest),
39        _ => return Err(USAGE.into()),
40    };
41    let command = parse_command(cmd_args)?;
42    println!("# record {}", cmd_args.join(" "));
43
44    let mut stream = TcpStream::connect(addr)?;
45    let mut buf = [0u8; 1024];
46
47    // Drain stale input (the idle server's periodic NAKs) for 500 ms.
48    let drain_end = Instant::now() + Duration::from_millis(500);
49    loop {
50        let left = drain_end.saturating_duration_since(Instant::now());
51        if left.is_zero() {
52            break;
53        }
54        stream.set_read_timeout(Some(left.max(Duration::from_millis(1))))?;
55        match stream.read(&mut buf) {
56            Ok(0) => return Err("connection closed".into()),
57            Ok(n) => println!("# stale: {}", escape(&buf[..n])),
58            Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => break,
59            Err(e) => return Err(e.into()),
60        }
61    }
62
63    let mut client = Client::new(Config::default());
64    client.start(Instant::now(), command)?;
65    let mut outcome: Option<bool> = None;
66    loop {
67        let now = Instant::now();
68        while let Some(bytes) = client.poll_output(now) {
69            stream.write_all(&bytes)?;
70            println!("> {}", escape(&bytes));
71        }
72        while let Some(event) = client.poll_event() {
73            eprintln!("{event:?}");
74            match event {
75                Event::Done => outcome = Some(true),
76                Event::Error(_) => outcome = Some(false),
77                _ => {}
78            }
79        }
80        let wait = match (client.next_timeout(), outcome) {
81            (None, Some(_)) => break,
82            (Some(t), _) => t.saturating_duration_since(now),
83            (None, None) => Duration::from_millis(100),
84        };
85        stream.set_read_timeout(Some(wait.max(Duration::from_millis(10))))?;
86        match stream.read(&mut buf) {
87            Ok(0) => return Err("connection closed".into()),
88            Ok(n) => {
89                println!("< {}", escape(&buf[..n]));
90                client.handle_input(Instant::now(), &buf[..n]);
91            }
92            Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {
93                client.handle_timeout(Instant::now());
94            }
95            Err(e) => return Err(e.into()),
96        }
97    }
98    std::io::stdout().flush()?;
99    if outcome == Some(true) {
100        Ok(())
101    } else {
102        std::process::exit(1);
103    }
104}
Source

pub fn is_idle(&self) -> bool

No transaction running and no linger after one (output may still be queued).

Source

pub fn cancel(&mut self, now: Instant)

Abort: queue an E packet “Cancelled”, emit Error(Cancelled), go idle. No-op when idle. During the linger after Done it only ends the linger: no E packet, no event.

Source

pub fn accepted(&self) -> u64

How many packets of the peer this client has taken as new since it was made: the server’s S answering the first packet, each packet of a receive with the next sequence number, each ACK (or NAK of the next packet) of the packet we sent. A repeated packet, a NAK, a damaged packet, an E packet and noise do not count, nor do the answers that end a transaction (Done and Error say so). A caller that sees it unchanged for longer than the client’s own retries can take knows the peer keeps the transaction alive without moving it on.

Source

pub fn peer_params(&self) -> Option<InitParams>

Parameters the peer sent in its S, or ACK to our S/I, in the current (or last finished) transaction; cleared by Client::start.

Trait Implementations§

Source§

impl Debug for Client

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Forget for Client

§

impl Freeze for Client

§

impl Move for Client

§

impl RefUnwindSafe for Client

§

impl Send for Client

§

impl Sync for Client

§

impl Unpin for Client

§

impl UnsafeUnpin for Client

§

impl UnwindSafe for Client

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.