-->

how to disable Nagle algorithm on TCP connection o

2020-06-17 14:51发布

问题:

I'm building a socket , using


CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault,
                                       (CFStringRef) yourHostAsNSString,
                                       yourPortAsInteger,
                                       &myReadStream,
                                       &myWriteStream);
and I see that when I send a messages with "myWriteStream" it concatenate few message together and then send them. I think it happens because of the Nagle algorithm and I want to disable it. Does any one knows how to do it?

回答1:

No guarantee this will fix your problem, but if you want to disable the Nagle algorithm, you need to get the native socket from the stream and call setsockopt.

CFDataRef nativeSocket = CFWriteStreamCopyProperty(myWriteStream, kCFStreamPropertySocketNativeHandle);
CFSocketNativeHandle *sock = (CFSocketNativeHandle *)CFDataGetBytePtr(nativeSocket);
setsockopt(*sock, IPPROTO_TCP, TCP_NODELAY, &(int){ 1 }, sizeof(int));
CFRelease(nativeSocket);

(Shout out to Mike Ash for the compound literal trick.)