Expand description
Provides simple cross-platform generic IPC message passing built on top of the interprocess
crate.
Examples
use interprocess::local_socket::NameTypeSupport;
use ipc_util::{send_ipc_message, send_ipc_query, start_ipc_listener, SocketExt};
use serde::{Deserialize, Serialize};
pub const MY_SOCKET_PATH: &str = "/tmp/ipc-util-ex-stream.sock";
pub const MY_SOCKET_NAMESPACE: &str = "@ipc-util-ex-stream.sock";
pub fn get_ipc_name() -> &'static str {
use NameTypeSupport::*;
match NameTypeSupport::query() {
OnlyPaths => MY_SOCKET_PATH,
OnlyNamespaced | Both => MY_SOCKET_NAMESPACE,
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum Message {
Text { text: String },
Ping,
Pong,
}
fn run_server() {
start_ipc_listener(
get_ipc_name(),
|mut stream| {
// Read message from client
let message: Message = stream.read_serde().expect("Failed to read message");
// Handle message
match message {
Message::Text { text } => {
println!("{text}");
}
Message::Ping => {
stream
.write_serde(&Message::Pong)
.expect("Failed to write pong");
}
_ => {}
};
},
None,
)
.expect("Failed to bind to socket")
.join()
.expect("Failed to join server thread");
}
fn run_client() {
let text = Message::Text {
text: "Hello from client!".to_string(),
};
let ping = Message::Ping;
send_ipc_message(get_ipc_name(), &text).expect("Failed to connect to socket");
let response: Message =
send_ipc_query(get_ipc_name(), &ping).expect("Failed to connect to socket");
dbg!(response);
}
fn main() {
let args = std::env::args().collect::<Vec<_>>();
match args.get(1).map(|s| s.as_str()) {
Some("server") => run_server(),
Some("client") => run_client(),
_ => {
println!("Usage: {} [server|client]", args[0]);
std::process::exit(1);
}
}
}
Enums
Traits
Functions
- Connects to the socket and returns the stream.
- Connects to the socket and writes a serializable object to it. Meant to be used for requests that don’t expect a response from the server.
- Connect to the socket and write a serializable object to it, then immediately read a deserializable object from it, blocking until a response is received. Meant to be used for requests that expect a response from the server.
- Attempts to spin up a thread that will listen for incoming connections on the given socket.
- A wrapper around
start_ipc_listener
.