Initial MeshPort SDK and cross-platform client
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
//! Reuse EasyTier's instance-scoped smoltcp plane rather than creating a second stack.
|
||||
use anyhow::{Result, ensure};
|
||||
pub use easytier_core::gateway::{
|
||||
DataPlaneTcpListener as TcpListener, DataPlaneTcpStream as TcpStream,
|
||||
DataPlaneUdpSocket as UdpSocket,
|
||||
};
|
||||
use std::{net::SocketAddr, time::Duration};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
pub async fn tcp_echo(
|
||||
stream: &mut TcpStream,
|
||||
payload: &[u8],
|
||||
timeout: Duration,
|
||||
) -> Result<Vec<u8>> {
|
||||
tokio::time::timeout(timeout, async {
|
||||
stream.write_all(payload).await?;
|
||||
let mut received = vec![0; payload.len()];
|
||||
stream.read_exact(&mut received).await?;
|
||||
ensure!(received == payload, "TCP echo data mismatch");
|
||||
Ok(received)
|
||||
})
|
||||
.await?
|
||||
}
|
||||
pub async fn udp_echo(
|
||||
socket: &UdpSocket,
|
||||
target: SocketAddr,
|
||||
payload: &[u8],
|
||||
timeout: Duration,
|
||||
) -> Result<Vec<u8>> {
|
||||
ensure!(
|
||||
payload.len() <= 65507,
|
||||
"UDP payload exceeds IPv4 datagram limit"
|
||||
);
|
||||
tokio::time::timeout(timeout, async {
|
||||
socket.send_to(payload, target).await?;
|
||||
let mut buffer = vec![0; 65535];
|
||||
loop {
|
||||
let (len, source) = socket.recv_from(&mut buffer).await?;
|
||||
if source != target {
|
||||
continue;
|
||||
}
|
||||
ensure!(&buffer[..len] == payload, "UDP echo data mismatch");
|
||||
return Ok(buffer[..len].to_vec());
|
||||
}
|
||||
})
|
||||
.await?
|
||||
}
|
||||
Reference in New Issue
Block a user