Sample code for 30+ languages & platforms
Java

Send a 4-byte Length Prefix over a Socket

See more Socket/SSL/TLS Examples

Demonstrates Socket.SendCount, which sends a four-byte length prefix in network byte order. This is typically used to tell the peer how many bytes follow.

Background. A length-prefixed framing scheme sends the byte count of a message before the message body, so the receiver knows exactly how many bytes to read with a counted receive.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Socket;

public class ChilkatExample {

    public static void main(String[] args) {
        Socket socket = new Socket();

        // Connect to the server using TLS.
        boolean bTls = true;
        int maxWaitMs = 5000;
        try {
            socket.connect("example.com", 5000, bTls, maxWaitMs);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // Send a four-byte length prefix in network byte order.  A common framing pattern is to send the
        // number of bytes in a message before the message itself, so the peer knows exactly how many bytes
        // to read.
        int messageLength = 512;
        try {
            socket.sendCount(messageLength);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        System.out.println("Length prefix sent.");
    }
}