Sample code for 30+ languages & platforms
Java

Receive a 4-byte Length Prefix from a Socket

See more Socket/SSL/TLS Examples

Demonstrates Socket.ReceiveCount, which reads a four-byte length prefix as a signed 32-bit integer. A return value of -1 indicates failure.

Background. Reading the length prefix first tells the application exactly how many bytes to read for the message body, which is a reliable way to know when a full message has arrived.

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;
        }

        // Read a four-byte length prefix as a signed 32-bit integer (network byte order by default).  A
        // return value of -1 indicates failure.
        int messageLength = socket.receiveCount();
        if (messageLength < 0) {
            System.out.println(socket.getLastErrorText());
            return;
        }

        System.out.println("The peer will send " + messageLength + " bytes.");
    }
}