Last active
November 6, 2023 08:14
-
-
Save tesaguri/b27d0d35d1a45465ddc9cb32a3ebe9ae to your computer and use it in GitHub Desktop.
Example code for inter-process communication in Rust using Unix domain socket.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "tokio-serde-json-ipc" | |
version = "0.0.0" | |
edition = "2018" | |
publish = false | |
[dependencies] | |
futures = "0.1" | |
serde_json = "1" | |
tokio = "0.1" | |
tokio-uds = "0.2" | |
[[bin]] | |
name = "server" | |
path = "src/server.rs" | |
[[bin]] | |
name = "client" | |
path = "src/client.rs" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use futures::Future; | |
use tokio::io; | |
use tokio_uds::UnixStream; | |
const PATH: &str = "test.sock"; | |
fn main() { | |
tokio::run( | |
UnixStream::connect(PATH) | |
.and_then(|sock| { | |
io::write_all(sock, serde_json::to_string("hello").unwrap().into_bytes()) | |
}) | |
.then(|r| { | |
r.unwrap(); | |
Ok(()) | |
}), | |
); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::env; | |
use std::fs; | |
use std::process::Command; | |
use futures::{Future, Stream}; | |
use tokio::io; | |
use tokio_uds::UnixListener; | |
const PATH: &str = "test.sock"; | |
fn main() { | |
let client = env::args().skip(1).next().expect("missing client command"); | |
let server = UnixListener::bind(PATH).unwrap(); | |
let mut client = Command::new(client).spawn().unwrap(); | |
tokio::run( | |
server | |
.incoming() | |
.into_future() | |
.map_err(|(e, _)| e) | |
.and_then(|(sock, _)| io::read_to_end(sock.unwrap(), Vec::new())) | |
.map(|bytes| { | |
println!("{}", serde_json::from_slice::<String>(&bytes.1).unwrap()) | |
}) | |
.map_err(|e| panic!("{:?}", e)), | |
); | |
client.wait().unwrap(); | |
fs::remove_file(PATH).unwrap(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment