1
0
Fork 0

Add unix example

This commit is contained in:
Florian RICHER 2023-01-24 08:58:52 +01:00
parent 49bab13f6e
commit b94c621ab1
No known key found for this signature in database
GPG key ID: 6BF27BF8A1E71623
9 changed files with 125 additions and 0 deletions

22
src/client/bin/main.rs Normal file
View file

@ -0,0 +1,22 @@
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(())
}

36
src/daemon/bin/main.rs Normal file
View file

@ -0,0 +1,36 @@
use std::os::unix::net::{UnixListener, UnixStream};
use anyhow::Context;
use std::io::{Read, Write};
fn main() -> anyhow::Result<()> {
let socket_path = "mysocket";
if std::fs::metadata(socket_path).is_ok() {
println!("A socket is already present. Deleting...");
std::fs::remove_file(socket_path).with_context(|| {
format!("could not delete previous socket at {:?}", socket_path)
})?;
}
let unix_listener =
UnixListener::bind(socket_path).context("Could not create the unix socket")?;
// put the daemon logic in a loop to accept several connections
loop {
let (mut unix_stream, socket_address) = unix_listener
.accept()
.context("Failed at accepting a connection on the unix listener")?;
handle_stream(unix_stream)?;
}
Ok(())
}
fn handle_stream(mut unix_stream: UnixStream) -> anyhow::Result<()> {
let mut message = String::new();
unix_stream
.read_to_string(&mut message)
.context("Failed at reading the unix stream")?;
println!("{}", message);
Ok(())
}