简单网络通信
在本章节中,我们将从一个简单的 HTTP 客户端以及服务器示例开始。然后在下个章节中,我们会介绍更为复杂的非阻塞示例。
HTTP 客户端的 如下。
使用如下命令来编译 Rust 程序。
使用如下命令在 WasmEdge 中运行程序。
wasmedge target/wasm32-wasi/release/http_client.wasm
HTTP 服务器的源代码 如下。
use bytecodec::DecodeExt;
use httpcodec::{HttpVersion, ReasonPhrase, Request, RequestDecoder, Response, StatusCode};
use std::io::{Read, Write};
#[cfg(feature = "std")]
use std::net::{Shutdown, TcpListener, TcpStream};
#[cfg(not(feature = "std"))]
use wasmedge_wasi_socket::{Shutdown, TcpListener, TcpStream};
fn handle_http(req: Request<String>) -> bytecodec::Result<Response<String>> {
Ok(Response::new(
HttpVersion::V1_0,
StatusCode::new(200)?,
ReasonPhrase::new("")?,
format!("echo: {}", req.body()),
))
}
fn handle_client(mut stream: TcpStream) -> std::io::Result<()> {
let mut buff = [0u8; 1024];
let n = stream.read(&mut buff)?;
data.extend_from_slice(&buff[0..n]);
if n < 1024 {
break;
}
}
let mut decoder =
RequestDecoder::<httpcodec::BodyDecoder<bytecodec::bytes::Utf8Decoder>>::default();
let req = match decoder.decode_from_bytes(data.as_slice()) {
Ok(req) => handle_http(req),
Err(e) => Err(e),
};
let r = match req {
Ok(r) => r,
Err(e) => {
let err = format!("{:?}", e);
HttpVersion::V1_0,
StatusCode::new(500).unwrap(),
err.clone(),
)
}
};
let write_buf = r.to_string();
stream.write(write_buf.as_bytes())?;
stream.shutdown(Shutdown::Both)?;
Ok(())
}
fn main() -> std::io::Result<()> {
let port = std::env::var("PORT").unwrap_or(1234.to_string());
println!("new connection at {}", port);
let listener = TcpListener::bind(format!("0.0.0.0:{}", port))?;
loop {
let _ = handle_client(listener.accept()?.0);
}
cargo build --target wasm32-wasi --release
使用如下命令在 WasmEdge 中运行程序。
$ wasmedge target/wasm32-wasi/release/http_server.wasm new connection at 1234