Implementing reliable chat and file transfer over UDP in Java
Heartbeats, a binary packet format, stop-and-wait ACKs and SHA-256 checks: rebuilding a bit of TCP on DatagramSocket.
TCP gives you a lot for free: ordered delivery, retransmission, connections that know when the other side has gone away. UDP gives you almost none of it. You send a datagram and hope. To understand what TCP is actually doing for me, I built two things in Java on top of plain DatagramSocket: a multi-user chat and a reliable file transfer tool.
UDP in one paragraph
A UDP socket sends and receives independent packets called datagrams. Each one either arrives whole or not at all. They can arrive out of order, arrive twice, or never arrive, and nothing tells you which. There's no connection, so the server doesn't know a client exists until a packet shows up, and doesn't know it's gone unless you build a way to tell.
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet); // blocks until any client sends something
InetAddress from = packet.getAddress();
int port = packet.getPort();
String text = new String(packet.getData(), 0, packet.getLength());Part 1: a chat server without connections
A tiny text protocol
Every message starts with a command:
JOIN:<username>registers a clientMSG:<text>broadcasts a messageLISTasks for online usersLEAVEsays goodbyePINGkeeps the client alive
Since there are no connections, the server identifies clients by where packets come from. The key is simply address:port:
private synchronized void processMessage(String message, InetAddress address, int port) {
String clientKey = address + ":" + port;
if (message.startsWith("JOIN:")) handleJoin(message.substring(5), address, port, clientKey);
else if (message.startsWith("MSG:")) handleMessage(message.substring(4), clientKey);
else if (message.startsWith("LEAVE")) handleLeave(clientKey);
else if (message.equals("LIST")) handleList(address, port);
else if (message.equals("PING")) handlePing(clientKey);
}Broadcasting is a loop that sends one datagram to every known client. There is no "send to all" in UDP unless you use multicast.
Knowing when someone left
With TCP, a closed connection tells you a client is gone. With UDP, a client that crashes or loses Wi-Fi just goes silent. So the protocol needs heartbeats:
The client sends
PINGevery 15 seconds from a background thread.The server records
lastSeenfor every client on any message.A cleanup thread runs every 10 seconds and removes clients that haven't been heard from in 30 seconds, announcing "has left the chat (timeout)".
boolean isActive() {
return System.currentTimeMillis() - lastSeen < CLIENT_TIMEOUT; // 30 s
}The timeout is twice the ping interval, so one lost PING doesn't kick anyone out. That ratio is the same trade-off every heartbeat system makes: shorter timeouts detect failures faster but cause more false alarms.
Part 2: reliable file transfer over an unreliable network
Chat can survive a lost message. A file can't survive a lost byte. This is where I had to rebuild a small piece of TCP.
Packet format
Every packet starts with a fixed 9-byte header:
[1 byte: type][4 bytes: sequence number][4 bytes: total packets][data...]Types are FILE_INFO, DATA, ACK, COMPLETE and ERROR. ByteBuffer makes the binary layout easy:
ByteBuffer buffer = ByteBuffer.allocate(HEADER_SIZE + data.length);
buffer.put(TYPE_DATA);
buffer.putInt(sequence);
buffer.putInt(total);
buffer.put(data);Why 1400 bytes?
A UDP datagram can be up to about 64 KB, but anything larger than the network's MTU (usually 1500 bytes on Ethernet) gets fragmented at the IP layer. If any fragment is lost, the whole datagram is lost. Capping packets at 1400 bytes leaves room for IP and UDP headers and keeps each datagram in a single frame.
Stop-and-wait with retries
The sender transmits one packet, then waits up to one second for an ACK. If none arrives, it sends again, up to three attempts:
private void sendPacketWithRetry(byte[] data) throws IOException {
for (int retry = 0; retry < MAX_RETRIES; retry++) {
socket.send(packet);
try {
socket.receive(ackPacket); // socket has a 1 s timeout
if (ackBuffer[0] == TYPE_ACK) return;
} catch (SocketTimeoutException e) {
// lost packet or lost ACK: try again
}
}
throw new IOException("No ACK after " + MAX_RETRIES + " attempts");
}The transfer has three phases:
FILE_INFOwith the file name, size and a SHA-256 hash.One
DATApacket per chunk, each acknowledged.COMPLETE, after which the receiver reassembles and verifies the file.
Duplicates and integrity
If an ACK is lost, the sender retransmits a packet the receiver already has. The receiver stores chunks in a map keyed by sequence number, so a duplicate simply overwrites itself. Reassembly walks sequence numbers from 0 to total - 1 and fails loudly if any are missing.
At the end, the receiver hashes the reassembled bytes and compares them with the hash from FILE_INFO:
String receivedHash = calculateHash(fileData); // SHA-256
if (!receivedHash.equals(expectedHash)) throw new IOException("File integrity check failed!");UDP has its own checksum, but it's only 16 bits and optional on IPv4. The end-to-end hash is what proves the file is correct.
What this taught me about TCP
Building even this much made it obvious why TCP is designed the way it is:
Stop-and-wait is slow. Only one packet is in flight at a time, so throughput is one packet per round trip. On a 50 ms link that's about 28 KB/s no matter how fast the network is. TCP uses a sliding window to keep many packets in flight. That's the next thing I want to build.
ACKs need sequence numbers. My ACK is a single byte. A delayed ACK for packet 4 could be mistaken for the ACK of packet 5. Real protocols acknowledge a specific sequence number.
Timeouts should adapt. A fixed one second timeout is too long on a LAN and too short on a bad mobile link. TCP estimates the round-trip time and adjusts.
Streaming beats buffering. The sender reads the whole file into memory and the receiver buffers everything before writing. Writing chunks as they arrive (in order) would handle files of any size.
UDP isn't "unreliable TCP". It's a blank page. Protocols like QUIC, DNS, game netcode and video calls all start from that page and add only the guarantees they need. Writing my own small version made that design space feel real instead of theoretical.
Discussion(0)
Loading comments…