1
0
Fork 0

create client and server.

main
Gökmen Görgen 1 month ago
parent 224b17ff1c
commit 5f8240632b
  1. 35
      src/client.rs
  2. 1
      src/lib.rs
  3. 38
      src/server.rs

@ -0,0 +1,35 @@
use std::io::{Read, Write};
use std::net::TcpStream;
use std::str::from_utf8;
fn make_request() {
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 as 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.");
}

@ -1 +1,2 @@
pub mod client;
pub mod server;

@ -1,6 +1,38 @@
use std::net::TcpListener;
use std::{
net::{Shutdown, TcpListener, TcpStream},
thread,
};
fn handle_client(mut stream: TcpStream) {
let mut data = [0 as u8; 50]; // using 50 byte buffer
while match stream(&mut data) {
Ok(size) => {
stream.write(&data[0..size]).unwrap();
true
}
Err(_) => {
eprintln!(
"An error occured, terminating connection with {}",
stream.peer_addr().unwrap()
);
stream.shutdown(Shutdown::Both).unwrap();
false
}
} {}
}
fn main() {
fn run_server() {
let listener = TcpListener::bind("0.0.0.0:3333").unwrap();
for stream in listener.incoming() {
match stream {
Ok(stream) => {
println!("New connection: {}", stream.peer_addr().unwrap());
thread::spawn(move || handle_client(stream));
}
Err(e) => {
eprintln!("Error: {}", e);
}
}
}
drop(listener);
}

Loading…
Cancel
Save