Question

I have implemented a client-server transferring from Windows desktop application to iPhone App. I transfer data using NSStream in polling mode (synchronous).

CFReadStreamRef readStream;
CFWriteStreamRef writeStream;

CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)urlStr, portNo, &readStream, &writeStream);

inputStream = (NSInputStream *)readStream;
outputStream = (NSOutputStream *)writeStream;

[inputStream open];
[outputStream open];

All works fine, but when I attempt to connect an inexistent server or a disconnected server or the port number/ip address is wrong, the WRITE method of NSOutputStream object, stops the application execution.

const uint8_t *str = (uint8_t *) [strRichiesta cStringUsingEncoding:NSASCIIStringEncoding];
[outputStream write:str maxLength:strlen((char*)str)]; 

Is it possible to manage the method by inserting timeout control? If yes, how can I do?

I think that the same problem occurs also with READ method of NSInputStream object.

Could someone help me, please?

Was it helpful?

Solution

Check the NSStreams' streamStatus and streamError functions before trying to use them for reading and writing. See Apple's NSStream Documentation for more info.

This also may help: Setting Up Socket Streams

EDIT: NSStreamStatus values:

typedef enum {
    NSStreamStatusNotOpen = 0,
    NSStreamStatusOpening = 1,
    NSStreamStatusOpen = 2,
    NSStreamStatusReading = 3,
    NSStreamStatusWriting = 4,
    NSStreamStatusAtEnd = 5,
    NSStreamStatusClosed = 6,
    NSStreamStatusError = 7
};

You will have to wait until the status is Open before using it. It may several seconds (maybe even 30 sec) for a bad URL to resolve to status Error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top