use std::io::prelude::*; use std::os::unix::net::{UnixListener, UnixStream}; use std::path::Path; fn handle_client(mut stream: UnixStream) -> std::io::Result<()> { let mut buf = [0; 1024]; let n = stream.read(&mut buf)?; let s = String::from_utf8_lossy(&buf[..n]); println!("{}", s); Ok(()) } fn main()-> Result<(), Box<dyn std::error::Error>> { let sockfile = Path::new("/tmp/uds.sock"); if sockfile.exists() { fs::remove_file(&sockfile)?; } let listner = UnixListener::bind(sockfile)?; for stream in listner.incoming() { let stream = stream?; thread::spawn(move || handle_client(stream).unwrap()); } Ok(()) }
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.28s
Running `target/debug/parallel`
これは基本的に、socketのincomingの待ち受け
use nix::unistd::{fork, getpid, getppid, ForkResult}; use std::thread; use std::fs; use std::io::prelude::*; use std::os::unix::net::{UnixListener, UnixStream}; use std::path::Path; use futures::StreamExt; use tokio; use tokio::io::AsyncReadExt; use tokio::net::unix::{UnixListener, UnixStream}; async fn handle_client(mut stream: UnixStream) -> Result<(), Box<dyn std::error::Error>> { let mut buf = [0; 1024]; let n = stream.read(&mut buf).await?; let s = String::from_utf8_lossy(&buf[..n]); println!("{}", s); Ok(()) } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { // let mut stm = UnixStream::connect("/tmp/uds.sock"); // stm?.write_all(b"hello world")?; let sockfile = Path::new("/tmp/uds.sock"); if sockfile.exists() { fs::remove_file(&sockfile)?; } let listner = UnixListener::bind(sockfile)?; let mut incoming = listner.incoming(); while let Some(stream) = incoming.next().await { let stream = stream?; tokio::spawn(async move { handle_client(stream).await.unwrap(); }); } Ok(()) }
動かない….
やりたいことはこれなんだが、これも上手くいかん…
use std::io::prelude::*; use std::os::unix::net::{UnixListener, UnixStream}; use std::thread; pub static SOCKET_PATH: &'static str = "rst.sock"; fn sender() { let name = "Sender".to_string(); let mut stream = UnixStream::connect(SOCKET_PATH).unwrap(); let messages = vec!["Hello", " ", "world!"]; for message in messages { stream.write_all(b"hello world").unwrap(); let mut response = String::new(); stream.read_to_string(&mut response).unwrap(); println!("{response}"); } } fn handle_client(mut stream: UnixStream) -> std::io::Result<()> { let mut buf = [0; 1024]; let n = stream.read(&mut buf)?; let s = String::from_utf8_lossy(&buf[..n]); println!("{}", s); Ok(()) } fn receiver() { let handle = thread::spawn(move || { let listner = UnixListener::bind(SOCKET_PATH).unwrap(); for stream in listner.incoming() { let stream = stream.unwrap(); thread::spawn(move || handle_client(stream).unwrap()); } }); handle.join().unwrap(); } fn main() { receiver(); sender(); }