rust hyper 实现 websocket 和http
时间: 2023-09-22 21:07:40 浏览: 281
Rust的Hyper库是一个基于tokio的异步HTTP库,它提供了一系列的API来处理HTTP请求和响应。同时,Hyper库也支持WebSocket的实现。
要使用Hyper库实现WebSocket,可以使用其提供的WebSocket模块。下面是一个简单的例子:
```rust
use hyper::{upgrade::Upgraded, service::service_fn_ok, Body, Request, Response, Server};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
use tokio::sync::broadcast;
use tokio::sync::Mutex;
use tungstenite::{Message, Result, WebSocket};
async fn handle_websocket(upgraded: Upgraded, tx: broadcast::Sender<String>, mut rx: broadcast::Receiver<String>) -> Result<()> {
let (ws_tx, mut ws_rx) = WebSocket::from_raw_socket(upgraded, tungstenite::protocol::Role::Server, None).await?;
let mut tx = tx.subscribe();
loop {
tokio::select! {
Some(msg) = ws_rx.next() => {
let msg = msg?;
if msg.is_text() {
let text_msg = msg.to_text().unwrap().to_owned();
tx.send(text_msg).unwrap();
}
}
Ok(msg) = rx.recv() => {
ws_tx.send(Message::Text(msg)).await?;
}
}
}
}
async fn handle_request(req: Request<Body>, tx: broadcast::Sender<String>, rx: broadcast::Receiver<String>) -> Result<Response<Body>> {
if req.uri().path() == "/websocket" {
let res = Response::builder()
.status(101)
.header("Sec-WebSocket-Accept", "...")
.body(Body::empty())
.unwrap();
let upgraded = req.into_body().on_upgrade().await?;
handle_websocket(upgraded, tx, rx).await?;
Ok(res)
} else {
let body = format!("Hello, {}!", req.uri().path());
let res = Response::new(Body::from(body));
Ok(res)
}
}
#[tokio::main]
async fn main() -> Result<()> {
let listener = TcpListener::bind("127.0.0.1:8080").await?;
let (tx, _) = broadcast::channel(10);
let rx = tx.subscribe();
let tx = Mutex::new(tx);
let server = Server::builder(listener.incoming())
.serve(move || {
let tx = tx.clone();
let rx = rx.clone();
service_fn_ok(move |req| handle_request(req, tx.lock().unwrap().clone(), rx.clone()))
});
server.await?;
Ok(())
}
```
上面的代码实现了一个简单的WebSocket服务器,同时也支持HTTP请求。当客户端发送一个WebSocket请求时,服务器会将连接升级为WebSocket连接,并通过广播的方式将收到的消息发送给所有客户端。当客户端发送一个HTTP请求时,服务器会返回一个简单的“Hello”消息。
对于HTTP请求,我们可以使用Hyper库提供的Request和Response类型来处理。对于WebSocket连接的处理,我们需要使用tungstenite库提供的WebSocket类型来处理。在这个例子中,我们使用了tokio的广播通道来实现消息的发送和接收。
阅读全文