chore: reorg

This commit is contained in:
2020-10-17 11:50:12 +08:00
parent a034988643
commit bb6762ab81
55 changed files with 0 additions and 0 deletions

5
__network/tcp/README.md Normal file
View File

@@ -0,0 +1,5 @@
from:
https://riptutorial.com/rust/example/4404/a-simple-tcp-client-and-server-application--echo

5
__network/tcp/tcp_client/Cargo.lock generated Normal file
View File

@@ -0,0 +1,5 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "udp_client"
version = "0.1.0"

View File

@@ -0,0 +1,9 @@
[package]
name = "udp_client"
version = "0.1.0"
authors = ["Hatter Jiang <jht5945@gmail.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,28 @@
use std::net::TcpStream;
use std::io::{ Read, Write };
use std::str::from_utf8;
fn main() {
match TcpStream::connect("localhost:3333") {
Ok(mut stream) => {
println!("Successfully connected to server in port 3333");
let msg = b"Hello!";
stream.write(msg).unwrap();
println!("Sent Hello, awaiting reply...");
let mut data = [0_u8; 6]; // using 6 byte buffer
match stream.read_exact(&mut data) {
Ok(_) => if &data == msg {
println!("Reply is ok!");
} else {
let text = from_utf8(&data).unwrap();
println!("Unexpected reply: {}", text);
},
Err(e) => println!("Failed to receive data: {}", e),
}
},
Err(e) => println!("Failed to connect: {}", e),
}
println!("Terminated.");
}

5
__network/tcp/tcp_server/Cargo.lock generated Normal file
View File

@@ -0,0 +1,5 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "udp_server"
version = "0.1.0"

View File

@@ -0,0 +1,9 @@
[package]
name = "udp_server"
version = "0.1.0"
authors = ["Hatter Jiang <jht5945@gmail.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,39 @@
use std::thread;
use std::net::{ TcpListener, TcpStream, Shutdown };
use std::io::{ Read, Write };
fn handle_client(mut stream: TcpStream) {
let mut data = [0_u8; 50]; // using 50 byte buffer
while match stream.read(&mut data) {
Ok(size) => {
// echo everything!
stream.write(&data[0..size]).unwrap();
true
},
Err(_) => {
println!("An error occurred, terminating connection with {}", stream.peer_addr().unwrap());
stream.shutdown(Shutdown::Both).unwrap();
false
},
} {}
}
fn main() {
let listener = TcpListener::bind("0.0.0.0:3333").unwrap();
// accept connections and process them, spawning a new thread for each one
println!("Server listening on port 3333");
for stream in listener.incoming() {
match stream {
Ok(stream) => {
println!("New connection: {}", stream.peer_addr().unwrap());
thread::spawn(move|| {
// connection succeeded
handle_client(stream)
});
},
Err(e) => println!("Error: {}", e),
}
}
// close the socket server
drop(listener);
}