how to disable Nagle algorithm on TCP connection on iPhone
Asked Answered
S

1

6

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?
Stephenstephenie answered 30/6, 2010 at 9:41 Comment(0)
G
6

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.)

Gorlicki answered 2/5, 2011 at 16:27 Comment(6)
+1 Great! Where did you insert this code? Right after CFStreamCreatePairWithSocketToHost I get a BAD_EXEC because the native socket is not already initiated.Maryjomaryl
If you're working at the CFNetwork level, call CFWriteStreamOpen first. The connection doesn't exist until open of the streams is opened. If your streams are NSStreams, use -[NSStream open].Gorlicki
I had to #import <netinet/tcp.h> for the TCP_NODELAY define. You could of course already have this in there depending on what else you're doing.Reamer
you'll also need to #import <netinet/in.h> for the IPPROTO_TCP` define and the setsockopt call itselfWalkup
If you're using NSStreams, you can't get the native socket directly after -[NSStream open]. You have to wait until your delegate receives NSStreamEventOpenCompleted via stream:handleEvent:.Altman
I tried this in the delegate callback stream:handleEvent but still get nil back from WriteStreamCopyProperty ?Metamorphosis

© 2022 - 2024 — McMap. All rights reserved.