Overview
ThePacket class represents a simulated network packet used in the Selective Repeat protocol. It provides immutable packet objects with a builder pattern for construction and methods for serialization/deserialization.
Packet Structure
Each packet consists of the following fields:Packet type identifier:
0: Data packet1: ACK (Acknowledgment)2: SYN (Connection request)3: SYN-ACK (Connection acknowledgment)4: NACK (Negative acknowledgment)6: Connection close
Packet sequence number for ordering and acknowledgment (unsigned 32-bit)
IPv4 address of the destination peer (4 bytes)
Destination port number (unsigned 16-bit)
Packet payload data (0-1024 bytes)
Constants
Packet header is 11 bytes: 1 (type) + 4 (sequence) + 4 (address) + 2 (port) = 11 bytes
Constructor
Packet()
Creates a new packet instance.Packet type (0-6)
Sequence number
Destination IP address
Destination port
Payload data
Getter Methods
getType()
Returns the packet type
getSequenceNumber()
Returns the sequence number
getPeerAddress()
Returns the destination IP address
getPeerPort()
Returns the destination port number
getPayload()
Returns the payload data as a byte array
Builder Pattern
Packet.Builder
Provides a fluent API for constructing packets.Builder Methods
setType()
setType()
setSequenceNumber()
setSequenceNumber()
setPeerAddress()
setPeerAddress()
setPortNumber()
setPortNumber()
setPayload()
setPayload()
create()
create()
toBuilder()
Creates a builder from an existing packet for modification.A new builder initialized with the current packet’s values
Serialization
toBytes()
Converts the packet to a byte array for network transmission.Raw byte representation of the packet in BigEndian format
toBuffer()
Converts the packet to a ByteBuffer in BigEndian format.ByteBuffer flipped and ready for reading
Deserialization
fromBytes()
Creates a packet from a byte array.Raw packet data received from network
Reconstructed packet object
fromBuffer()
Creates a packet from a ByteBuffer.ByteBuffer containing packet data in BigEndian format
Reconstructed packet object
Byte Format
Packets are encoded in BigEndian byte order:String Representation
toString()
Returns a human-readable string representation.Formatted string with sequence number, peer address, port, and payload size
Packet Type Reference
Data (0)
Regular data packet containing payload
ACK (1)
Acknowledgment of received packet
SYN (2)
Connection initiation request
SYN-ACK (3)
Connection acknowledgment
NACK (4)
Negative acknowledgment
CLOSE (6)
Connection termination
Example Usage
See Also
ReliableClientProtocol
Client-side protocol using packets
ServerTcpProtocl
Server-side protocol using packets