-
Notifications
You must be signed in to change notification settings - Fork 75
/
receiver.rs
75 lines (65 loc) · 2.87 KB
/
receiver.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
use super::common::{SenderMsg, ReceiverMsg};
use message_io::network::{NetEvent, Transport, Endpoint};
use message_io::node::{self};
use std::collections::{HashMap};
use std::fs::{File};
use std::io::{Write};
pub struct Transfer {
file: File,
name: String,
current_size: usize,
expected_size: usize,
}
pub fn run() {
let (handler, listener) = node::split::<()>();
let listen_addr = "127.0.0.1:3005";
handler.network().listen(Transport::FramedTcp, listen_addr).unwrap();
println!("Receiver running by TCP at {}", listen_addr);
let mut transfers: HashMap<Endpoint, Transfer> = HashMap::new();
listener.for_each(move |event| match event.network() {
NetEvent::Connected(_, _) => unreachable!(),
NetEvent::Accepted(_, _) => (),
NetEvent::Message(endpoint, input_data) => {
let message: SenderMsg = bincode::deserialize(&input_data).unwrap();
match message {
SenderMsg::FileRequest(name, size) => {
let able = match File::create(format!("{}.recv", name)) {
Ok(file) => {
println!("Accept file: '{}' with {} bytes", name, size);
let transfer =
Transfer { file, name, current_size: 0, expected_size: size };
transfers.insert(endpoint, transfer);
true
}
Err(_) => {
println!("Can not open the file to write");
false
}
};
let output_data = bincode::serialize(&ReceiverMsg::CanReceive(able)).unwrap();
handler.network().send(endpoint, &output_data);
}
SenderMsg::Chunk(data) => {
let transfer = transfers.get_mut(&endpoint).unwrap();
transfer.file.write(&data).unwrap();
transfer.current_size += data.len();
let current = transfer.current_size as f32;
let expected = transfer.expected_size as f32;
let percentage = ((current / expected) * 100.0) as usize;
print!("\rReceiving '{}': {}%", transfer.name, percentage);
if transfer.expected_size == transfer.current_size {
println!("\nFile '{}' received!", transfer.name);
transfers.remove(&endpoint).unwrap();
}
}
}
}
NetEvent::Disconnected(endpoint) => {
// Unexpected sender disconnection. Cleaning.
if transfers.contains_key(&endpoint) {
println!("\nUnexpected Sender disconnected");
transfers.remove(&endpoint);
}
}
});
}