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

wappered by napi, the tokio::net::TcpStream never get ready to read until TcpStream::write() #2089

Open
ape-casear opened this issue May 6, 2024 · 0 comments

Comments

@ape-casear
Copy link

all code is here.

#[macro_use]
extern crate napi_derive;
use napi::bindgen_prelude::Result;
use std::time::Duration;
use std::{io, thread};
use tokio::io::Interest;
use tokio::net::TcpStream;

#[napi(object)]
pub struct CmdMessage {
    pub cmd: u32,
    pub body_str: String,
}

/// create tcpclient 
#[napi]
pub fn create_tcp_stream() -> Result<()> {
    tokio::spawn(start_tcp_loop());
    Ok(())
}

async fn start_tcp_loop() {
    let tcp: std::prelude::v1::Result<TcpStream, std::io::Error> =
        TcpStream::connect("127.0.0.1:8899").await;
    let tcp = match tcp {
        Ok(stream) => stream,
        Err(_e) => {
            eprintln!("connect fail");
            return;
        }
    };

    let mut buf = [0; 1024];
    loop {
        let mut slee_this_tick = true;
        let ready = tcp
            .ready(Interest::READABLE | Interest::WRITABLE)
            .await
            .expect("msg");

        println!(
            "ready for reading:{}, ready for writing:{}",
            ready.is_readable(),
            ready.is_writable()
        );
        let resp = tcp.try_read(&mut buf);
        if let Ok(size) = resp {
            slee_this_tick = false;
            if size == 0 {
                break;
            } else {
                // process_buf(&mut buf[..size], &mut status);
            }
        } else if let Err(e) = resp {
            if e.kind() != io::ErrorKind::WouldBlock {
                eprintln!("connect failed, error:{}", e);
            }
        }
        if slee_this_tick {
            println!("sleeping");
            thread::sleep(Duration::from_millis(4000));
        }
    }
}

on another terminal, I got an NC server setup by nc -l 8899;
and I type something and press the Enter button. the output is always "ready for reading: false"

@ape-casear ape-casear changed the title wappered by napi tokio::net::TcpStream never get ready to read until TcpStream::write() wappered by napi, the tokio::net::TcpStream never get ready to read until TcpStream::write() May 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant