12 个版本 (3 个稳定版本)

1.0.3 2024 年 7 月 25 日
0.4.2 2024 年 5 月 9 日
0.4.1 2023 年 8 月 8 日
0.4.0 2023 年 6 月 27 日
0.1.1 2021 年 11 月 23 日

#42 in WebSocket

Download history 78/week @ 2024-04-24 19/week @ 2024-05-01 490/week @ 2024-05-08 636/week @ 2024-05-15 553/week @ 2024-05-22 547/week @ 2024-05-29 767/week @ 2024-06-05 855/week @ 2024-06-12 1106/week @ 2024-06-19 850/week @ 2024-06-26 659/week @ 2024-07-03 854/week @ 2024-07-10 409/week @ 2024-07-17 402/week @ 2024-07-24 594/week @ 2024-07-31 622/week @ 2024-08-07

每月 2,186 次下载
用于 10 Crates (7 个直接使用)

Apache-2.0

295KB
7K SLoC




Ratchet

Ratchet 是一个快速、健壮、轻量级且完全异步的 RFC6455 (WebSocket 协议) 实现。还包括 RFC7692 (WebSocket 压缩扩展) 的可选实现。

特性

  • 使用 ratchet_ext 实现自己的扩展。
  • 使用 ratchet_deflate 进行按消息的 deflate 或通过 deflate 功能启用。
  • 使用 split 功能分割 WebSocket。

测试

Ratchet 完全经过测试,并且通过了客户端和服务器模式下的所有 Autobahn 测试。

示例

客户端

#[tokio::main]
async fn main() -> Result<(), Error> {
  let stream = TcpStream::connect("127.0.0.1:9001").await?;
  
  let upgraded = subscribe(
    WebSocketConfig::default(),
    stream,
    "ws://127.0.0.1/hello".try_into_request()?,
  )
  .await?;

  let UpgradedClient{ socket, subprotocol }=upgraded;
  let mut buf = BytesMut::new();

  loop {
    match websocket.read(&mut buf).await? {
      Message::Text => {
        websocket.write(&mut buf, PayloadType::Text).await?;
        buf.clear();
      }
      Message::Binary => {
        websocket.write(&mut buf, PayloadType::Binary).await?;
        buf.clear();
      }
      Message::Ping | Message::Pong => {
        // Ping messages are transparently handled by Ratchet
      }
      Message::Close(_) => break Ok(()),
    }
  }
}

服务器

#[tokio::main]
async fn main() -> Result<(), Error> {
    let listener = TcpListener::bind("127.0.0.1:9001").await?;
    let mut incoming = TcpListenerStream::new(listener);

    while let Some(socket) = incoming.next().await {
        let socket = socket?;

        // An upgrader contains information about what the peer has requested.
        let mut upgrader = ratchet::accept_with(
            socket,
            WebSocketConfig::default(),
            NoExtProvider,
            ProtocolRegistry::default(),
        )
        .await?;

        // You could opt to reject the connection
        // upgrader.reject(WebSocketResponse::new(404)?).await?;
        // continue;
      
        // Or you could reject the connection with headers
        // upgrader.reject(WebSocketResponse::with_headers(404, headers)?).await;
        // continue;

        let UpgradedServer {
            request,
            mut websocket,
            subprotocol,
        } = upgrader.upgrade().await?;
        
        let mut buf = BytesMut::new();

        loop {
            match websocket.read(&mut buf).await? {
                Message::Text => {
                    websocket.write(&mut buf, PayloadType::Text).await?;
                    buf.clear();
                }
                Message::Binary => {
                    websocket.write(&mut buf, PayloadType::Binary).await?;
                    buf.clear();
                }
                Message::Ping | Message::Pong => {
                  // Ping messages are transparently handled by Ratchet
                }
                Message::Close(_) => break,
            }
        }
    }
    
    Ok(())
}

Deflate

  let mut websocket = ratchet::accept_with(
      socket,
      WebSocketConfig::default(),
      DeflateProvider,
      ProtocolRegistry::default(),
  )
  .await?;

Split

// A split operation will only fail if the WebSocket is already closed.
let (mut sender, mut receiver) = websocket.split()?;
    
loop {
    match receiver.read(&mut buf).await? {
        Message::Text => {
            sender.write(&mut buf, PayloadType::Text).await?;
            buf.clear();
        }
        Message::Binary => {
            sender.write(&mut buf, PayloadType::Binary).await?;
            buf.clear();
        }
        Message::Ping | Message::Pong => {}
        Message::Close(_) => break Ok(()),
    }
}

计划中的特性

  • futures-rs SinkStream 实现。
  • tokio AsyncReadAsyncWrite 实现。

许可证

Ratchet 根据 Apache License 2.0 许可。

依赖

~13–25MB
~326K SLoC