backup.rs 3.06 KiB
use std::io::prelude::*;
use std::io::{stdout, stdin};
use std::fmt;
use std::net::{IpAddr, Ipv4Addr};
use std::net::TcpStream;
use std::net::TcpListener;
//Message Size
const BUFFER_SIZE: usize = 4;
fn main() {
    //Listener
    let ip = IpAddr::V4(Ipv4Addr::new(10, 240, 200, 171));
    let port: u32 = 7777;
    //Sender
    let target_ip = IpAddr::V4(Ipv4Addr::new(130, 240, 200, 93));
    let target_port: u32 = 7777;
    //let ip = IpAddr::V4(Ipv4Addr::new(127,0,0,1));
    //let port: u32 = 7878;
    //Sender
    //let target_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
    //let target_port: u32 = 7878;
    loop {
        print!("Please choose function:\n1. Send\n2. Receive\n====> ");
        stdout().flush().unwrap();
        let mut choice = String::new();
        stdin().read_line(&mut choice).expect("Incorrect input");
        let choice: u32 = match choice.trim().parse() {
            Ok(num) => num,
            Err(_) => continue,
        print!("You picked: ");
        match choice {
            1 =>  { println!("Send!\nSending data...");
                sender(target_ip, target_port);
                println!("Data has been sent!\n");
            2 => { println!("Listen!\nListening for data...");
                listener(ip, port);
                println!("Data has been listened to!\n");
            _ => println!("Incorrect option!\n"),
    listener(ip, port);
    //sender(target_ip, target_port);
// Done
fn sender(ip: IpAddr, port: u32) {
    //Sets up connection.
	let mut stream = TcpStream::connect(format!("{}:{}", ip, port)).unwrap();
    let response = "This is a test sentence and will have only been successfully transmitted \
    if the text on screen show three x:es in a row at the very end. This marks the end of the test value. xxx";
    stream.write(response.as_bytes()).unwrap(); //Sends TCP data
    stream.flush().unwrap();
//Listens to TCP stream for data to be Printed in Console.
fn listener(ip: IpAddr, port: u32){
    // Set up the listener to an IP and a Port.
71727374757677787980818283848586878889909192939495969798
let listener = TcpListener::bind(format!("{}:{}", ip, port)).unwrap(); // For as long as there is data in the TCP queue, keep printing. for stream in listener.incoming() { let stream = stream.unwrap(); print_message(stream); //Prints the data from the TCP stream println!("\n---Data has been listened to!---\n-------------------------------"); } } fn print_message(mut stream: TcpStream) { let mut buffer = [0; BUFFER_SIZE]; // Set a buffer to store TCP stream data. println!("\n---Message Received:---"); // While there's still data in buffer let mut peek:usize = stream.peek(&mut buffer).expect("peek failed"); while peek > 0 { if peek < BUFFER_SIZE{ buffer = [0; BUFFER_SIZE]; //Clears the buffer } stream.read(&mut buffer).unwrap(); print!("{}", String::from_utf8_lossy(&buffer[..])); stdout().flush().unwrap(); //Prints the message peek = stream.peek(&mut buffer).expect("peek failed"); } }