Objective-C
Objective-C
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 Objective-C Downloads
#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;
}
// 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] intValue];
if (messageLength < 0) {
NSLog(@"%@",socket.LastErrorText);
return;
}
NSLog(@"%@%d%@",@"The peer will send ",messageLength,@" bytes.");