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.
It seem like if the socket does not flush data waiting on the buffer before closing.
Here is my code:
int port = 1234;
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (CFStringRef)host, port, &readStream, &writeStream);
if (readStream && 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 *)&len maxLength:4];
[outputStream write:[data bytes] maxLength:[data length]];
if (inputStream) {
CFReadStreamClose((CFReadStreamRef)inputStream);
CFRelease(inputStream);
}
if (outputStream) {
CFWriteStreamClose((CFWriteStreamRef)outputStream);
CFRelease(outputStream);
}
All ideas are appreciated
Jens
You could try waiting until CFWriteStreamGetStatus returns kCFStreamStatusAtEnd before closing it. I think that the problem is the CFWriteStreamClose automatically releases the string from everywhere that uses it, including where the data is actually being pushed to the network, meaning it leaves unpushed data in the buffer when it’s freed. This should guarantee that all data has been pushed out before it is flushed.
http://developer.apple.com/library/mac/#documentation/CoreFoundation/Reference/CFWriteStreamRef/Reference/reference.html