1*6046f775S裕依 use std::io::{Error, Read, Write}; 2*6046f775S裕依 use std::os::unix::net::{UnixListener, UnixStream}; 3*6046f775S裕依 use std::thread; 4*6046f775S裕依 use std::{fs, str}; 5*6046f775S裕依 6*6046f775S裕依 const SOCKET_PATH: &str = "/test.socket"; 7*6046f775S裕依 const MSG: &str = "Hello, unix stream socket!"; 8*6046f775S裕依 client() -> std::io::Result<()>9*6046f775S裕依fn client() -> std::io::Result<()> { 10*6046f775S裕依 // 连接到服务器 11*6046f775S裕依 let mut stream = UnixStream::connect(SOCKET_PATH)?; 12*6046f775S裕依 // 发送消息到服务器 13*6046f775S裕依 stream.write_all(MSG.as_bytes())?; 14*6046f775S裕依 Ok(()) 15*6046f775S裕依 } 16*6046f775S裕依 test_unix_stream() -> std::io::Result<()>17*6046f775S裕依pub fn test_unix_stream() -> std::io::Result<()> { 18*6046f775S裕依 println!("unix stream socket path: {}", SOCKET_PATH); 19*6046f775S裕依 // 删除可能已存在的socket文件 20*6046f775S裕依 fs::remove_file(&SOCKET_PATH).ok(); 21*6046f775S裕依 // 创建Unix域监听socket 22*6046f775S裕依 let listener = UnixListener::bind(SOCKET_PATH)?; 23*6046f775S裕依 24*6046f775S裕依 let client_thread = thread::spawn(move || client()); 25*6046f775S裕依 26*6046f775S裕依 // 监听并接受连接 27*6046f775S裕依 let (mut stream, _) = listener.accept().expect("listen error"); 28*6046f775S裕依 29*6046f775S裕依 let mut buffer = [0; 1024]; 30*6046f775S裕依 let nbytes = stream.read(&mut buffer).expect("read error"); 31*6046f775S裕依 let received_msg = str::from_utf8(&buffer[..nbytes]).unwrap(); 32*6046f775S裕依 33*6046f775S裕依 client_thread.join().ok(); 34*6046f775S裕依 35*6046f775S裕依 fs::remove_file(&SOCKET_PATH).ok(); 36*6046f775S裕依 37*6046f775S裕依 if received_msg == MSG { 38*6046f775S裕依 Ok(()) 39*6046f775S裕依 } else { 40*6046f775S裕依 Err(Error::from_raw_os_error(-1)) 41*6046f775S裕依 } 42*6046f775S裕依 } 43