Module tcp_handler::compress_encrypt
source · Available on crate features
compression
and encrypt
only.Expand description
Compression and encryption protocol.
Recommended to use this protocol.
§Example
use anyhow::Result;
use bytes::{Buf, BufMut, BytesMut};
use flate2::Compression;
use tcp_handler::compress_encrypt::*;
use tokio::net::{TcpListener, TcpStream};
use variable_len_reader::{VariableReader, VariableWriter};
#[tokio::main]
async fn main() -> Result<()> {
let server = TcpListener::bind("localhost:0").await?;
let mut client = TcpStream::connect(server.local_addr()?).await?;
let (mut server, _) = server.accept().await?;
let level = Compression::default();
let c_init = client_init(&mut client, &"test", &"0").await;
let s_init = server_init(&mut server, &"test", |v| v == "0").await;
let mut s_cipher = server_start(&mut server, s_init).await?;
let mut c_cipher = client_start(&mut client, c_init).await?;
let mut writer = BytesMut::new().writer();
writer.write_string("hello server.")?;
let mut bytes = writer.into_inner();
c_cipher = send(&mut client, &mut bytes, c_cipher, level).await?;
let (reader, s) = recv(&mut server, s_cipher).await?;
let mut reader = reader.reader(); s_cipher = s;
let message = reader.read_string()?;
assert_eq!("hello server.", message);
let mut writer = BytesMut::new().writer();
writer.write_string("hello client.")?;
let mut bytes = writer.into_inner();
s_cipher = send(&mut server, &mut bytes, s_cipher, level).await?;
let (reader, c) = recv(&mut client, c_cipher).await?;
let mut reader = reader.reader(); c_cipher = c;
let message = reader.read_string()?;
assert_eq!("hello client.", message);
Ok(())
}
This protocol is like this:
┌────┬────────┬────────────┐ (It may not be in contiguous memory.)
in --> │ ** │ ****** │ ********** │
└────┴────────┴────────────┘
Nonce │
| │
v │
┌────┐ │
│ ** │ ─│
└────┘ │
│─ DeflateEncoder
v
┌──────────────────────┐ (Compressed bytes. In contiguous memory.)
│ ******************** │
└──────────────────────┘
│
│─ Encrypt in-place
v
┌──────────────────────┐ (Compressed and encrypted bytes.)
out <-- │ ******************** │
└──────────────────────┘
Functions§
- Init the client side in tcp-handler compress_encrypt protocol.
- Make sure the client side is ready to use in tcp-handler compress_encrypt protocol.
- Recv message in compress_encrypt tcp-handler protocol.
- Send message in compress_encrypt tcp-handler protocol.
- Init the server side in tcp-handler compress_encrypt protocol.
- Make sure the server side is ready to use in tcp-handler compress_encrypt protocol.