This repository contains a demonstration TCP and UDP packet communication in Rust using tokio.
Client view:
Server view:
The tcp_udp crate defines a Packet structure that can be serialized and deserialized for network transmission. It provides methods for sending and receiving packets over tokio::net::TcpStream and tokio::net::UdpSocket.
The main.rs example demonstrates a UDP server that:
- Listens for incoming UDP packets.
- Deserializes the received packets.
- Prints the packet ID and payload.
- Sends an "echo" packet back to the sender.
- Sends a heartbeat message every 5 seconds.
src/lib.rs: Defines thePacketstruct and its associated methods for serialization, deserialization, and sending/receiving over TCP/UDP.src/main.rs: Contains the main application logic, implementing a UDP server.src/client.rs: a client for sending encrypted messages (Run with$ cargo run --bin client)
The Packet struct has the following fields:
id: Au16representing the packet's identifier.payload: AVec<u8>containing the packet's data.
serialize(): Converts aPacketinto a byte vector. The format is[id (2 bytes)] + [payload].deserialize(): Converts a byte slice back into aPacket.
send(&self, stream: &mut TcpStream): Asynchronously sends the packet over aTcpStream. The packet is prefixed with its total length (including ID and payload) as au16.recv(stream: &mut TcpStream): Asynchronously receives a packet from aTcpStream. It first reads the packet length, then the ID, and finally the payload.
- Rust and Cargo: If you don't have Rust installed, you can get it from rustup.rs.
-
Clone the repository:
git clone <repository_url> cd <repository_name>
-
Run the example:
cargo run
This will start the UDP server listening on
127.0.0.1:8080. You will see heartbeat messages in the console.
You can use a tool like netcat (or nc) or write a simple client to send UDP packets to the server.
Example using netcat:
Open another terminal and send a message:
echo -n -e "\x00\x01Hello" | nc -u 127.0.0.1 8080\x00\x01: Represents the 2-byte packet ID (here,1in big-endian).Hello: Is the payload.
The server will then print something
To update rust:
rustup self update
Then run:
rustup update
Then try:
cargo clean
cargo build
cargo run
