nonblock_tcp_stream.rs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. use std::io::{Read, Write};
  2. use std::thread::sleep;
  3. use std::time::Duration;
  4. use wasmedge_wasi_socket::{Shutdown, TcpStream};
  5. fn main() -> std::io::Result<()> {
  6. let port = std::env::var("PORT").unwrap_or("1234".to_string());
  7. println!("connect to 127.0.0.1:{}", port);
  8. let mut stream = TcpStream::connect(format!("127.0.0.1:{}", port))?;
  9. stream.set_nonblocking(true)?;
  10. println!("sending hello message");
  11. stream.write(b"Hello\n")?;
  12. loop {
  13. let mut buf = [0; 128];
  14. match stream.read(&mut buf) {
  15. Ok(0) => {
  16. println!("server closed connection");
  17. break;
  18. }
  19. Ok(size) => {
  20. let buf = &mut buf[..size];
  21. println!("get response: {}", String::from_utf8_lossy(buf));
  22. stream.shutdown(Shutdown::Both)?;
  23. break;
  24. }
  25. Err(e) => {
  26. if e.kind() == std::io::ErrorKind::WouldBlock {
  27. println!("no data available, wait for 500ms");
  28. sleep(Duration::from_millis(500));
  29. } else {
  30. return Err(e);
  31. }
  32. }
  33. };
  34. }
  35. Ok(())
  36. }