Last active
June 12, 2018 03:32
-
-
Save jakebromberg/e66b937cd87ab06d4a50532d5b3fc4fe to your computer and use it in GitHub Desktop.
Disables Nagle's Algorithm on a TCP socket
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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