2 个版本

0.1.1 2021 年 9 月 18 日
0.1.0 2021 年 9 月 18 日

#438HTTP 服务器

Download history 1585/week @ 2024-03-14 2247/week @ 2024-03-21 2000/week @ 2024-03-28 1903/week @ 2024-04-04 1604/week @ 2024-04-11 2620/week @ 2024-04-18 3085/week @ 2024-04-25 1441/week @ 2024-05-02 1064/week @ 2024-05-09 1555/week @ 2024-05-16 659/week @ 2024-05-23 1780/week @ 2024-05-30 1772/week @ 2024-06-06 1479/week @ 2024-06-13 1330/week @ 2024-06-20 835/week @ 2024-06-27

5,713 每月下载量

MIT 许可证

21KB
364

慕斯

一个 SSE 编解码器

用法

解码

use futures::stream::StreamExt;
use mousse::Parser;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let url = match std::env::args().nth(1) {
        Some(url) => url,
        None => {
            eprintln!("expected uri argument\ncargo run -- <uri>");
            std::process::exit(1);
        }
    };
    let mut stream = reqwest::get(&url)
        .await?
        .bytes_stream();
    while let Some(chunk) = stream.next().await {
        let chunk = chunk?;
        let string = String::from_utf8_lossy(&chunk);
        let mut parser = Parser::new(&string);
        println!("{:?}", parser.next_event());
    }
    Ok(())
}

输出

如果您将其连接到 SSE 服务器,您可能会看到类似以下内容。

cargo run --example reqwest -- http://localhost:8080/sse
Some(ServerSentEvent { comment: None, event: None, id: None, data: Some("next tick in 5"), retry: None })
Some(ServerSentEvent { comment: Some(""), event: None, id: None, data: None, retry: None })
Some(ServerSentEvent { comment: None, event: None, id: None, data: Some("next tick in 4"), retry: None })
Some(ServerSentEvent { comment: Some(""), event: None, id: None, data: None, retry: None })
Some(ServerSentEvent { comment: None, event: None, id: None, data: Some("next tick in 2"), retry: None })
Some(ServerSentEvent { comment: None, event: None, id: None, data: Some("next tick in 1"), retry: None })

编码

use mousse::ServerSentEvent;

fn main() {
    for i in 0..10 {
        println!(
            "{}",
            ServerSentEvent::builder()
                .data(&format!("{}: Hi I am a data field", i))
                .id(&i.to_string())
                .build()
        )
    }
}

输出

cargo run --example encode
id:0
data:0: Hi I am a data field


id:1
data:1: Hi I am a data field


id:2
data:2: Hi I am a data field


id:3
data:3: Hi I am a data field


id:4
data:4: Hi I am a data field


id:5
data:5: Hi I am a data field


id:6
data:6: Hi I am a data field


id:7
data:7: Hi I am a data field


id:8
data:8: Hi I am a data field


id:9
data:9: Hi I am a data field


依赖关系

~87KB