Language syntax

TCP length-prefixed framing

Validate the byte count before allocation and read exactly that frame.

Formal Syntax & Structure

java syntaxjava
out.writeInt(bytes.length); out.write(bytes);

Working Example

Example Snippetjava
import java.io.*;import java.net.*;import java.net.http.*;import java.nio.*;import java.nio.channels.*;import java.nio.charset.StandardCharsets;import java.time.Duration;import java.util.*;import java.util.concurrent.*;import com.sun.net.httpserver.HttpServer;public class Main {    static final InetAddress LOOP = InetAddress.getLoopbackAddress();    static void writeFrame(DataOutputStream out, String text) throws IOException {        byte[] bytes = text.getBytes(StandardCharsets.UTF_8);        if (bytes.length > 64) throw new IOException("frame too large");        out.writeInt(bytes.length); out.write(bytes); out.flush();    }    static String readFrame(DataInputStream in) throws IOException {        int length = in.readInt();        if (length < 0 || length > 64) throw new IOException("invalid length");        byte[] bytes = new byte[length]; in.readFully(bytes);        return StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes)).toString();    }    static void exchange(String value) throws Exception {        try (ServerSocket server = new ServerSocket(0, 1, LOOP);             var worker = Executors.newSingleThreadExecutor()) {            server.setSoTimeout(3000);            var response = worker.submit(() -> {                try (Socket peer = server.accept()) {                    peer.setSoTimeout(3000);                    String received = readFrame(new DataInputStream(peer.getInputStream()));                    writeFrame(new DataOutputStream(peer.getOutputStream()), "OK:" + received);                    return received;                }            });            try (Socket client = new Socket(Proxy.NO_PROXY)) {                client.connect(new InetSocketAddress(LOOP, server.getLocalPort()), 3000);                client.setSoTimeout(3000);                writeFrame(new DataOutputStream(client.getOutputStream()), value);                System.out.println(readFrame(new DataInputStream(client.getInputStream())));                if (!response.get(3, TimeUnit.SECONDS).equals(value)) throw new AssertionError();            }        }    }    public static void main(String[] args) throws Exception {        exchange("A17");    }}
Java Reference