Skip to content

Instantly share code, notes, and snippets.

@itsgreggreg
Created March 29, 2020 19:57
Show Gist options
  • Save itsgreggreg/326172e04587fb5029e290ca24228cbb to your computer and use it in GitHub Desktop.
Save itsgreggreg/326172e04587fb5029e290ca24228cbb to your computer and use it in GitHub Desktop.
Rust TCP client where you are the client
//! A simple TCP client where you are the client
//! An authority must be supplied, ie: cargo run -- pop.dreamhost.com:110
//!
//! Reads from and writes to stdio
//! Does nothing special with the incoming stream, simply prints 8bit chars.
//! Removes new lines from outbound stream, appends CR/LF.
use std::io::{stdin, stdout, Read, Write};
use std::net::TcpStream;
fn main() {
let args: Vec<String> = std::env::args().collect();
let authority = args
.get(1)
.expect("An authority (url:port-no) must be given");
match TcpStream::connect(authority) {
Ok(stream) => {
println!("Successfully connected to server");
let mut listener = stream;
let mut sayer = listener
.try_clone()
.expect("Could not clone the TCP stream");
// In this thread we simply listen for chars and print them
// as they come in, will not handle multibyte chars correctly
let listen = std::thread::spawn(move || loop {
let mut read: &mut [u8] = &mut [0];
let _ = listener.read(&mut read);
match std::str::from_utf8(&read) {
Ok(printable) => print!("{}", printable),
Err(_) => (),
};
});
// In this thread we wait for line based user input. Remove
// newlines and append CR/LF
let say = std::thread::spawn(move || loop {
let mut input = String::new();
let _ = stdout().flush();
stdin().read_line(&mut input).expect("Input not understood");
if let Some('\n') = input.chars().next_back() {
input.pop();
}
if let Some('\r') = input.chars().next_back() {
input.pop();
}
sayer
.write_fmt(format_args!("{}\r\n", input))
.expect("Could not write to stream");
});
// Wait on both threads to end.
let _ = say.join();
let _ = listen.join();
}
Err(e) => {
println!("Failed to connect: {}", e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment