1个不稳定版本

0.1.0 2021年3月19日

#2504 in 开发工具


用于 tokio-tls-helper

MIT 许可证

7KB

Tokio TLS Helper

此代码基于tonic进行修改和衍生,简化了使用TLS来保护您的tokio TCP应用的过程。

使用方法

服务器

// you could also build your config with cert and identity separately. See tests.
let config: ServerTlsConfig = toml::from_str(config_file).unwrap();
let acceptor = config.tls_acceptor().unwrap();
let listener = TcpListener::bind(addr).await.unwrap();
tokio::spawn(async move {
    loop {
        let (stream, peer_addr) = listener.accept().await.unwrap();
        let stream = acceptor.accept(stream).await.unwrap();
        info!("server: Accepted client conn with TLS");

        let fut = async move {
            let (mut reader, mut writer) = split(stream);
            let n = copy(&mut reader, &mut writer).await?;
            writer.flush().await?;
            debug!("Echo: {} - {}", peer_addr, n);
        }

        tokio::spawn(async move {
            if let Err(err) = fut.await {
                error!("{:?}", err);
            }
        });
    }
});

客户端

let msg = b"Hello world\n";
let mut buf = [0; 12];

// you could also build your config with cert and identity separately. See tests.
let config: ClientTlsConfig = toml::from_str(config_file).unwrap();
let connector = config.tls_connector(Uri::from_static("localhost")).unwrap();

let stream = TcpStream::connect(addr).await.unwrap();
let mut stream = connector.connect(stream).await.unwrap();
info!("client: TLS conn established");

stream.write_all(msg).await.unwrap();

info!("client: send data");

let (mut reader, _writer) = split(stream);

reader.read_exact(buf).await.unwrap();

info!("client: read echoed data");

注意:TLS是保护TCP连接的多种选择之一,您也可以考虑snow,它实现了Noise协议

许可证

tokio-tls-helper 在MIT许可下分发。

有关详细信息,请参阅LICENSE

版权所有 2021 Tyr Chen

依赖项

~2.2–8MB
~46K SLoC