Sample code for 30+ languages & platforms
PHP

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 PHP Downloads

Chilkat2 PHP
<?php

use Chilkat2\Socket;

$socket = new Socket();

// Connect to the server using TLS.
$bTls = true;
$maxWaitMs = 5000;
try {
    $socket->Connect('example.com', 5000, $bTls, $maxWaitMs);
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

// Read a four-byte length prefix as a signed 32-bit integer (network byte order by default).  A
// return value of -1 indicates failure.
$messageLength = $socket->ReceiveCount();
if ($messageLength < 0) {
    echo $socket->LastErrorText, "\n";
    exit;
}

echo 'The peer will send ', $messageLength, " bytes.\n";