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?
Aurelio De Rosa
  • 21,856
  • 8
  • 48
  • 71
gkedmi
  • 61
  • 1
  • 4

1 Answers1

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

Steve Madsen
  • 13,465
  • 4
  • 49
  • 67
  • +1 Great! Where did you insert this code? Right after CFStreamCreatePairWithSocketToHost I get a BAD_EXEC because the native socket is not already initiated. – rjobidon Dec 04 '11 at 03:48
  • 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]`. – Steve Madsen Dec 07 '11 at 21:16
  • 3
    I had to `#import ` for the TCP_NODELAY define. You could of course already have this in there depending on what else you're doing. – WiseOldDuck Sep 19 '12 at 22:26
  • you'll also need to `#import for the `IPPROTO_TCP` define and the `setsockopt` call itself – divillysausages Jul 18 '13 at 09:20
  • 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:`. – jonahb Mar 04 '14 at 02:41
  • I tried this in the delegate callback stream:handleEvent but still get nil back from WriteStreamCopyProperty ? – bobmoff May 23 '14 at 18:45