Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add server side to network worker #20

Merged
merged 1 commit into from
Apr 11, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions src/worker/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,53 @@ impl NetworkWorker {
workload: workload,
}
}

/// Start a simple server. The client side is going to be a networking
/// worker as well, so for convenience of troubleshooting do not error
/// out if something unexpected happened, log and proceed instead.
fn start_server(
&self,
addr: Ipv4Address,
target_port: u16,
) -> Result<(), WorkerError> {
let listener =
TcpListener::bind((addr.to_string(), target_port)).unwrap();

for stream in listener.incoming() {
let mut stream = stream.unwrap();
loop {
let mut buf_reader = BufReader::new(&stream);
let mut buffer = String::new();

match buf_reader.read_line(&mut buffer) {
Ok(0) => {
// EOF, exit
break;
}
Ok(_n) => {
trace!("Received {:?}", buffer);

let response = "hello\n";
match stream.write_all(response.as_bytes()) {
Ok(_) => {
// Response is sent, handle the next one
break;
}
Err(e) => {
trace!("ERROR: sending response, {}", e);
break;
}
}
}
Err(e) => {
trace!("ERROR: reading a line, {}", e)
}
}
}
}

Ok(())
}
}

impl Worker for NetworkWorker {
Expand All @@ -53,6 +100,12 @@ impl Worker for NetworkWorker {
unreachable!()
};

let ip_addr = Ipv4Address([address.0, address.1, address.2, address.3]);

if server {
let _ = self.start_server(ip_addr, target_port);
}

Ok(())
}
}
Expand Down
Loading