1
0
Fork 0

Add sample server + client unix socket

This commit is contained in:
Florian RICHER 2023-01-24 14:17:32 +01:00
parent b94c621ab1
commit 6d1582792c
No known key found for this signature in database
GPG key ID: 6BF27BF8A1E71623
8 changed files with 127 additions and 27 deletions

View file

@ -1,22 +0,0 @@
use std::os::unix::net::{UnixListener, UnixStream};
use std::io::{Read, Write};
use anyhow::Context;
fn main() -> anyhow::Result<()> {
let socket_path = "mysocket";
let mut unix_stream =
UnixStream::connect(socket_path).context("Could not create stream")?;
unix_stream
.write(b"Hello?") // we write bytes, &[u8]
.context("Failed at writing onto the unix stream")?;
Ok(())
}
fn handle_stream(mut stream: UnixStream) -> anyhow::Result<()> {
// to be filled
Ok(())
}

41
src/client/main.rs Normal file
View file

@ -0,0 +1,41 @@
use std::os::unix::net::{UnixListener, UnixStream};
use std::io::{Read, Write};
use anyhow::Context;
fn main() -> anyhow::Result<()> {
let socket_path = "mysocket";
let mut unix_stream =
UnixStream::connect(socket_path).context("Could not create stream")?;
write_request_and_shutdown(&mut unix_stream)?;
read_from_stream(&mut unix_stream)?;
Ok(())
}
fn write_request_and_shutdown(unix_stream: &mut UnixStream) -> anyhow::Result<()> {
unix_stream
.write(b"Hello?")
.context("Failed at writing onto the unix stream")?;
println!("We sent a request");
println!("Shutting down writing on the stream, waiting for response...");
unix_stream
.shutdown(std::net::Shutdown::Write)
.context("Could not shutdown writing on the stream")?;
Ok(())
}
fn read_from_stream(unix_stream: &mut UnixStream) -> anyhow::Result<()> {
let mut response = String::new();
unix_stream
.read_to_string(&mut response)
.context("Failed at reading the unix stream")?;
println!("We received this response: {}", response);
Ok(())
}

View file

1
src/common/mod.rs Normal file
View file

@ -0,0 +1 @@
pub mod internal_rpc;

View file

@ -22,7 +22,6 @@ fn main() -> anyhow::Result<()> {
.context("Failed at accepting a connection on the unix listener")?;
handle_stream(unix_stream)?;
}
Ok(())
}
fn handle_stream(mut unix_stream: UnixStream) -> anyhow::Result<()> {
@ -31,6 +30,10 @@ fn handle_stream(mut unix_stream: UnixStream) -> anyhow::Result<()> {
.read_to_string(&mut message)
.context("Failed at reading the unix stream")?;
println!("{}", message);
println!("We received this message: {}\nReplying...", message);
unix_stream
.write(b"I hear you!")
.context("Failed at writing onto the unix stream")?;
Ok(())
}

1
src/lib.rs Normal file
View file

@ -0,0 +1 @@
pub(self) mod common;