Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Disables Nagle's Algorithm on a TCP socket
// Nagle's algorithm is a means of improving the efficiency of TCP/IP networks by reducing the number of packets that need to
// be sent over the network.
// https://en.wikipedia.org/wiki/Nagle%27s_algorithm
#import <netinet/in.h>
#import <netinet/tcp.h>
@implementation NSStream (DisableNaglesAlgorithm)
- (void)disableNaglesAlgorithmWithError:(NSError **)error {
CFDataRef data;
// Get socket data
if ([self isKindOfClass:[NSOutputStream class]]) {
data = CFWriteStreamCopyProperty(
(__bridge CFWriteStreamRef)((NSOutputStream *)self),
kCFStreamPropertySocketNativeHandle
);
} else if ([self isKindOfClass:[NSInputStream class]]) {
data = CFReadStreamCopyProperty(
(__bridge CFReadStreamRef)((NSInputStream *)self),
kCFStreamPropertySocketNativeHandle
);
}
// get a handle to the native socket
CFSocketNativeHandle handle;
CFDataGetBytes(data, CFRangeMake(0, sizeof(CFSocketNativeHandle)), (UInt8 *)&handle);
CFRelease(data);
// Disable Nagle's algorithm
int err;
static const int kOne = 1;
err = setsockopt(handle, IPPROTO_TCP, TCP_NODELAY, &kOne, sizeof(kOne));
if (err < 0) {
err = errno;
*error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{
NSLocalizedDescriptionKey : @"Error disabling Nagle's algorithm"
}];
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment