Arduino极客 发表于 2021-6-11 11:04:03

UnixSocket编程双工通信例子

客户端发送66(int32),服务端判断是奇偶并返回Boolean

use std::{io::{Read, Write}, os::unix::net::{UnixListener, UnixStream}};

#
enum Message {
    I32(i32),
    Bool(bool)
}

const UNIX_SOCK_ADDR: &str = "/home/w/temp/my_sock.sock11";

#
fn unix_socket_server() -> Result<(), Box<dyn std::error::Error>> {
    let listener = UnixListener::bind(UNIX_SOCK_ADDR)?;
    for mut stream in listener.incoming().flatten() {
      //stream.recv_vectored_with_ancillary(bufs, ancillary);
      let mut read_buffer = Vec::new();
      stream.read_to_end(&mut read_buffer)?;
      let request: Message = bincode::deserialize(&read_buffer[..])?;
      println!("Server Incomming Request: {:?}", request);
      let response = match request {
            Message::I32(int) => Message::Bool(int % 2 == 1),
            _ => panic!("unsupported message type")
      };
      println!("Server Preprare Reponse: {:?}", response);
      // stream.write(&bincode::serialize(&response)?)?;
      // stream.flush()?;
      stream.shutdown(std::net::Shutdown::Both);
    }
    Ok(())
}

#
fn unix_socket_client() -> Result<(), Box<dyn std::error::Error>> {
    let mut stream = UnixStream::connect(UNIX_SOCK_ADDR)?;
    let request = Message::I32(66);
    stream.write(&bincode::serialize(&request)?)?;
    stream.flush()?;
    Ok(())
}
页: [1]
查看完整版本: UnixSocket编程双工通信例子