title: Open Socket, Send Data, Close Socket = Truncated data
body: <p>I am having trouble sending data on a socket from an iphone application I am developing.
  In short, i want to connect to a tcp server on a specific port, send a data payload and then close the socket.</p>
  
  <p>It seem like if the socket <strong>does not flush</strong> data waiting on the buffer before closing.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>int port = 1234;
  CFReadStreamRef readStream;
  CFWriteStreamRef writeStream;
  CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (CFStringRef)host, port, &amp;readStream, &amp;writeStream);
  if (readStream &amp;&amp; writeStream) {
      //CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
      CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
  
      inputStream = (NSInputStream *)readStream;
      [inputStream retain];
      [inputStream setDelegate:self];
      [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
      [inputStream open];
  
      outputStream = (NSOutputStream *)writeStream;
      [outputStream retain];
      [outputStream setDelegate:self];
      [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
      [outputStream open];
  }
  
  [outputStream write:(void *)&amp;len maxLength:4];
  [outputStream write:[data bytes] maxLength:[data length]];
  
  if (inputStream) {
      CFReadStreamClose((CFReadStreamRef)inputStream);
      CFRelease(inputStream);
  }
  if (outputStream) {
      CFWriteStreamClose((CFWriteStreamRef)outputStream);
      CFRelease(outputStream);
  }   
  </code></pre>
  
  <p>All ideas are appreciated</p>
  
  <p>Jens</p>