smol/examples/windows-uds.rs

48 lines
1.3 KiB
Rust
Raw Normal View History

2020-04-21 15:51:07 +00:00
// TODO: document
2020-03-31 16:04:16 +00:00
#[cfg(windows)]
fn main() -> std::io::Result<()> {
2020-04-19 09:29:52 +00:00
use std::path::PathBuf;
2020-03-31 16:04:16 +00:00
use futures::io;
use futures::prelude::*;
2020-04-18 13:29:24 +00:00
use smol::{Async, Task};
2020-04-19 09:29:52 +00:00
use tempfile::tempdir;
2020-03-31 16:04:16 +00:00
use uds_windows::{UnixListener, UnixStream};
async fn client(addr: PathBuf) -> io::Result<()> {
2020-04-18 13:29:24 +00:00
let stream = Async::new(UnixStream::connect(addr)?)?;
2020-03-31 16:04:16 +00:00
println!("Connected to {:?}", stream.get_ref().peer_addr()?);
let mut stdout = smol::writer(std::io::stdout());
io::copy(&stream, &mut stdout).await?;
Ok(())
}
2020-04-19 09:29:52 +00:00
let dir = tempdir()?;
let path = dir.path().join("socket");
2020-03-31 16:04:16 +00:00
smol::run(async {
// Create a listener.
2020-04-19 09:29:52 +00:00
let listener = Async::new(UnixListener::bind(&path)?)?;
2020-03-31 16:04:16 +00:00
println!("Listening on {:?}", listener.get_ref().local_addr()?);
// Spawn a client task.
2020-04-19 09:29:52 +00:00
let task = Task::spawn(client(path));
2020-03-31 16:04:16 +00:00
// Accept the client.
2020-04-08 14:40:03 +00:00
let (stream, _) = listener.with(|l| l.accept()).await?;
2020-03-31 16:04:16 +00:00
println!("Accepted a client");
// Send a message, drop the stream, and wait for the client.
Async::new(stream)?.write_all(b"Hello!\n").await?;
task.await?;
Ok(())
})
}
#[cfg(not(windows))]
fn main() {
println!("This example works only on Windows!");
}