Skip to content

Instantly share code, notes, and snippets.

@jakebromberg
Last active June 12, 2018 03:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakebromberg/e66b937cd87ab06d4a50532d5b3fc4fe to your computer and use it in GitHub Desktop.
Save jakebromberg/e66b937cd87ab06d4a50532d5b3fc4fe to your computer and use it in GitHub Desktop.
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