1
votes

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

1
How do you know outputStream does not send anything? Try checking the return value of write:maxLength. If it's -1 you can obtain further details calling [outputStream streamError]. - Manlio
@PavelChuchuva Most of the time it works. I think that 99% of the sends goes thru to my server however maybe 1% I get a connection to my server but no data is received. @ThomasMinor gave me some hints below which made me eventually try to wait for a NSStreamEventHasSpaceAvailable event before closing the socket, however I am not sure if it has side effects. Maybe it will close the socket while sending a large block of data? Thanks for helping - www.jensolsson.se

1 Answers

0
votes

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