Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add read/try methods to NamedPipeServer #3899

Merged
merged 1 commit into from
Jun 29, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 63 additions & 9 deletions examples/named-pipe-ready.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::io;

#[cfg(windows)]
async fn windows_main() -> io::Result<()> {
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, Interest};
use tokio::io::Interest;
use tokio::net::windows::named_pipe::{ClientOptions, ServerOptions};

const PIPE_NAME: &str = r"\\.\pipe\named-pipe-single-client";
Expand All @@ -13,11 +13,62 @@ async fn windows_main() -> io::Result<()> {
// Note: we wait for a client to connect.
server.connect().await?;

let mut server = BufReader::new(server);
let buf = {
let mut read_buf = [0u8; 5];
let mut read_buf_cursor = 0;

loop {
server.readable().await?;

let buf = &mut read_buf[read_buf_cursor..];

match server.try_read(buf) {
Ok(n) => {
read_buf_cursor += n;

if read_buf_cursor == read_buf.len() {
break;
}
}
Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
continue;
}
Err(e) => {
return Err(e);
}
}
}

read_buf
};

{
let write_buf = b"pong\n";
let mut write_buf_cursor = 0;

loop {
let buf = &write_buf[write_buf_cursor..];

if buf.is_empty() {
break;
}

server.writable().await?;

match server.try_write(buf) {
Ok(n) => {
write_buf_cursor += n;
}
Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
continue;
}
Err(e) => {
return Err(e);
}
}
}
}

let mut buf = String::new();
server.read_line(&mut buf).await?;
server.write_all(b"pong\n").await?;
Ok::<_, io::Error>(buf)
});

Expand All @@ -33,9 +84,12 @@ async fn windows_main() -> io::Result<()> {
let mut write_buf_cursor = 0;

loop {
let ready = client
.ready(Interest::READABLE | Interest::WRITABLE)
.await?;
let mut interest = Interest::READABLE;
if write_buf_cursor < write_buf.len() {
interest |= Interest::WRITABLE;
}

let ready = client.ready(interest).await?;

if ready.is_readable() {
let buf = &mut read_buf[read_buf_cursor..];
Expand Down Expand Up @@ -85,7 +139,7 @@ async fn windows_main() -> io::Result<()> {

let (server, client) = tokio::try_join!(server, client)?;

assert_eq!(server?, "ping\n");
assert_eq!(server?, *b"ping\n");
assert_eq!(client?, "pong\n");

Ok(())
Expand Down
Loading