Tuesday, July 5, 2011

Disable Nagle algorithm (TCP_NODELAY) in Cocoa AsyncSocket library

#import // for IPPROTO_TCP
#include // for TCP_NODELAY
- (void)onSocket:(AsyncSocket *)sock
didConnectToHost:(NSString *)host port:(UInt16)port
{
NSLog(@"client - didConnectToHost");
// etc etc ..

// Add exactly the following code to disable Nagling:
CFSocketRef cfsock = [sock getCFSocket];
CFSocketNativeHandle rawsock = CFSocketGetNative(cfsock);
int flag = 1;
int result = setsockopt(rawsock, IPPROTO_TCP, TCP_NODELAY,
(char *)&flag, sizeof(int));
if (result != 0)
NSLog(@"Could Not Disable Nagle...");
else
NSLog(@"Nagle Is Disabled.");
}
}
Note that you need the two includes, just for the two constants mentioned in the code. Source