Sockets are often used in client / server applications, in which centralized service waits for various remote machines to request specific resources, because the client initiates the communication with the server
TCP Client
pub fn connect(address: &str) -> Result<(), failure::Error> {
// TcpStream to create a stream
// connect, to connect to a remote host
let mut stream = TcpStream::connect(address)?;
loop {
// accept input
// let to introduce a variable
// mut to bind value to variable name
// String::new() to create a new String in memory
let mut input = String::new();
// read input
// stdin() to stream the input
// read_line to read a line of input
io::stdin().read_line(&mut input)?;
// write input
// write_all to write entire buffer
// as_bytes() to convert string to byte
stream.write_all(input.as_bytes())?;
// BufRead reader to perform reading
// BufReader to add buffer to reader
let mut reader = BufReader::new(&stream);
// Vec to create a vector to store values
let mut buffer = Vec::new();
// read_until to read until the delimiter
// or EOF is found
reader.read_until(b’\n’, &mut buffer)?;
// from_utf8 to convert bytes to a string
print!("{}", str::from_utf8(&buffer)?);
}
}
TCP Server
pub fn serve(address: &str) -> Result<(), failure::Error> {
// TcpListener to listen for connection
// bind, to bind to a socket server address
let listener = TcpListener::bind(address)?;
loop {
// accept, to accept an incoming connection
// from listener
let (stream, _) = listener.accept()?;
// to create a new thread
thread::spawn(move || {
//
handler(stream).unwrap_or_else(|error| error!("{:?}", error));
});
}
}
//
fn handler(mut stream: TcpStream) -> Result<(), failure::Error> {
// to return the remote address this stream is connected to
// to debug the address of a TcpStream
debug!("Address {}", stream.peer_addr()?);
// buffer
// is a memory block for temporary data storage
// create a buffer with a capacity of 1024 bytes
let mut buffer = [0u8; 1024];
loop {
// to read data from the stream into the provided buffer
let nbytes = stream.read(&mut buffer)?;
// if number of bytes equals to 0
if nbytes == 0 {
return Ok(());
}
// str::from_utf8 - to decode a slice of UTF-8 bytes to string slices
println!("{}", str::from_utf8(&buffer[..nbytes])?);
// to write number of bytes from the buffer
stream.write_all(&buffer[..nbytes])?;
}
}
Thanks