#telnet #tokio-codec #mud #tcp-stream #gmcp #mssp #mccp

nectar

通过 Tokio 编码器实现的 Telnet 协议(RFC 854)。包括对各种 MUD 协议扩展的支持。

4 个版本 (破坏性)

0.4.0 2024 年 5 月 27 日
0.3.0 2024 年 4 月 7 日
0.2.0 2024 年 3 月 30 日
0.1.0 2023 年 2 月 18 日

#331网络编程

每月 44 次下载

MIT/Apache

115KB
2K SLoC

nectar

nectar 是一个 Tokio 编码器,提供了部分 Telnet 协议(RFC 854)的实现。

支持主要协商选项:DO、DONT、WILL、WONT。支持子协商(NAWS、自定义字节序列)。旨在实现一些流行的 MUD 协议扩展。

用法

只需在您的根项目目录中简单使用 cargo add nectar

您还必须使用具有 codec 特性的 tokio-utils 以及 tokio

如果您想深入了解编码器,请参阅 Tokio 文档。本质上,它只是以结构化方式对底层 TCP 流进行编码和解码的一种方式 - 在这种情况下,我们的结构是 Telnet 协议。

示例

请参阅 echo_server 目录中的带注释代码的示例。如果您已克隆了 nectar 仓库,则可以使用 cargo 运行 echo 服务器,然后使用 telnet localhost 5000 连接。

注意:请确保检查示例 Cargo.toml 文件中的依赖项。

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let addr = SocketAddr::from(([127, 0, 0, 1], 5000));
    let listener = TcpListener::bind(addr).await?;

    println!("telnet server started on: {}", addr);

    // Standard Tokio setup - we accept new connections and pass the
    // stream off to our handler function where the real work happens.
    loop {
        while let Ok((stream, _)) = listener.accept().await {
            tokio::spawn(async move {
                if let Err(e) = handler(stream).await {
                    eprintln!("error: {}", e);
                }
            });
        }
    }
}

async fn handler(stream: TcpStream) -> Result<(), Box<dyn std::error::Error>> {
    // We construct a 'Frame', which is just a wrapper around the underlying
    // stream that is decoded by the `nectar::TelnetCodec`.
    let mut frame = Framed::new(stream, TelnetCodec::new(1024));

    // In a real application, you would want to handle Some(Err(_)) and None
    // variants, but for this example we'll be succinct for simplicities sake.
    while let Some(Ok(msg)) = frame.next().await {
        match msg {
            // We'll keep it simple and only match against the Message event.
            TelnetEvent::Message(string) => {
                // Let's echo back what we received.
                frame.send(TelnetEvent::Message(string)).await?;
            }
            _ => break,
        }
    }
}

您可以通过查看 Blossom 源代码来了解在更复杂、现实场景中 nectar 的示例。

许可证

nectar 源代码可在以下任一许可证下使用:

由您选择。

依赖项

~2.4–3.5MB
~54K SLoC