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