Sample code for 30+ languages & platforms
Objective-C

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 Objective-C Downloads

Objective-C
#import <CkoSocket.h>

BOOL success = NO;

CkoSocket *socket = [[CkoSocket alloc] init];

//  Connect to the server using TLS.
BOOL bTls = YES;
int maxWaitMs = 5000;
success = [socket Connect: @"example.com" port: [NSNumber numberWithInt: 5000] ssl: bTls maxWaitMs: [NSNumber numberWithInt: maxWaitMs]];
if (success == NO) {
    NSLog(@"%@",socket.LastErrorText);
    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;
success = [socket SendCount: [NSNumber numberWithInt: messageLength]];
if (success == NO) {
    NSLog(@"%@",socket.LastErrorText);
    return;
}

NSLog(@"%@",@"Length prefix sent.");