This commit is contained in:
Myx
2024-08-20 19:36:39 +02:00
commit 271a01ce30
9 changed files with 826 additions and 0 deletions

18
src/client.rs Normal file
View File

@@ -0,0 +1,18 @@
use futures_util::{StreamExt, TryStreamExt}; // Add TryStreamExt
use tokio_tungstenite::connect_async;
use tokio_tungstenite::tungstenite::protocol::Message;
use url::Url;
pub async fn run_client(addr: &str) {
let url = Url::parse(&format!("ws://{}", addr)).expect("Invalid URL");
let (ws_stream, _) = connect_async(url).await.expect("Failed to connect");
let (_, mut read) = ws_stream.split(); // Use try_split instead of split
while let Some(msg) = read.next().await {
let msg = msg.expect("Failed to read message");
if let Message::Binary(data) = msg {
tokio::fs::write("received_file.png", data).await.expect("Failed to write file");
println!("File received and saved as received_file.png");
}
}
}

BIN
src/main.exe Normal file

Binary file not shown.

BIN
src/main.pdb Normal file

Binary file not shown.

15
src/main.rs Normal file
View File

@@ -0,0 +1,15 @@
mod server;
mod client;
use tokio::task;
#[tokio::main]
async fn main() {
let server_addr = "127.0.0.1:8080";
let file_path = "c:/shared/file.jpg";
let server = task::spawn(server::run_server(server_addr, file_path));
let client = task::spawn(client::run_client(server_addr));
let _ = tokio::join!(server, client);
}

27
src/server.rs Normal file
View File

@@ -0,0 +1,27 @@
use futures_util::{SinkExt, StreamExt};
use tokio::net::TcpListener;
use tokio_tungstenite::accept_async;
use tokio_tungstenite::tungstenite::protocol::Message;
use std::path::Path;
use tokio::fs::File;
use tokio::io::AsyncReadExt;
pub async fn run_server(addr: &str, file_path: &str) {
let listener = TcpListener::bind(addr).await.expect("Failed to bind");
println!("Server listening on {}", addr);
while let Ok((stream, _)) = listener.accept().await {
let file_path = file_path.to_string();
tokio::spawn(async move {
let ws_stream = accept_async(stream).await.expect("Error during the websocket handshake");
let (mut write, _) = ws_stream.split();
let path = Path::new(&file_path);
let mut file = File::open(path).await.expect("Failed to open file");
let mut buffer = Vec::new();
file.read_to_end(&mut buffer).await.expect("Failed to read file");
write.send(Message::Binary(buffer)).await.expect("Failed to send file");
});
}
}