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