简单网络通信

    在本章节中,我们将从一个简单的 HTTP 客户端以及服务器示例开始。然后在下个章节中,我们会介绍更为复杂的非阻塞示例。

    HTTP 客户端的 如下。

    使用如下命令来编译 Rust 程序。

    使用如下命令在 WasmEdge 中运行程序。

    wasmedge target/wasm32-wasi/release/http_client.wasm

    HTTP 服务器的源代码 如下。

    1. use bytecodec::DecodeExt;
    2. use httpcodec::{HttpVersion, ReasonPhrase, Request, RequestDecoder, Response, StatusCode};
    3. use std::io::{Read, Write};
    4. #[cfg(feature = "std")]
    5. use std::net::{Shutdown, TcpListener, TcpStream};
    6. #[cfg(not(feature = "std"))]
    7. use wasmedge_wasi_socket::{Shutdown, TcpListener, TcpStream};
    8. fn handle_http(req: Request<String>) -> bytecodec::Result<Response<String>> {
    9. Ok(Response::new(
    10. HttpVersion::V1_0,
    11. StatusCode::new(200)?,
    12. ReasonPhrase::new("")?,
    13. format!("echo: {}", req.body()),
    14. ))
    15. }
    16. fn handle_client(mut stream: TcpStream) -> std::io::Result<()> {
    17. let mut buff = [0u8; 1024];
    18. let n = stream.read(&mut buff)?;
    19. data.extend_from_slice(&buff[0..n]);
    20. if n < 1024 {
    21. break;
    22. }
    23. }
    24. let mut decoder =
    25. RequestDecoder::<httpcodec::BodyDecoder<bytecodec::bytes::Utf8Decoder>>::default();
    26. let req = match decoder.decode_from_bytes(data.as_slice()) {
    27. Ok(req) => handle_http(req),
    28. Err(e) => Err(e),
    29. };
    30. let r = match req {
    31. Ok(r) => r,
    32. Err(e) => {
    33. let err = format!("{:?}", e);
    34. HttpVersion::V1_0,
    35. StatusCode::new(500).unwrap(),
    36. err.clone(),
    37. )
    38. }
    39. };
    40. let write_buf = r.to_string();
    41. stream.write(write_buf.as_bytes())?;
    42. stream.shutdown(Shutdown::Both)?;
    43. Ok(())
    44. }
    45. fn main() -> std::io::Result<()> {
    46. let port = std::env::var("PORT").unwrap_or(1234.to_string());
    47. println!("new connection at {}", port);
    48. let listener = TcpListener::bind(format!("0.0.0.0:{}", port))?;
    49. loop {
    50. let _ = handle_client(listener.accept()?.0);
    51. }

    cargo build --target wasm32-wasi --release

    使用如下命令在 WasmEdge 中运行程序。

    $ wasmedge target/wasm32-wasi/release/http_server.wasm new connection at 1234