Lukas
Lukas

Reputation: 1366

iOS TCP / IP Check connection

I'm currently trying to connect to a tcp server. Everything works really good, but if the server is not available, the app freeze about 30 seconds and that's not really nice. I've searched for a resolution, but couldn't find something usefull so far.

Maybe someone of you have got a solution to check a connection?

    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)@"IP_SERVER_PATH", 6666, &readStream, &writeStream);
    inputStream = (__bridge NSInputStream *)readStream;
    outputStream = (__bridge NSOutputStream *)writeStream;
    [inputStream setDelegate:self];
    [outputStream setDelegate:self];
    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [inputStream open];
    [outputStream open];

Upvotes: 0

Views: 2397

Answers (3)

tony gil
tony gil

Reputation: 9564

as H2CO3 said: you are hanging for 30 seconds because of faulty design (if you are only testing, ok): you should never put anything with potentially long / indeterminate periods of waiting (external connection, for example) in your main thread.

having said that, i would recommend that you make your app behave like messaging systems do: commit external communication check to a thread that happens in the background while the user moves on to other (non dependent) steps.

IF NETWORK DATA VOLUME IS NOT A PROBLEM, put a background thread on a timer, constantly checking your connection by sending "heartbeat" or "stayalive" messages, like this example. that way, while your user merrily does her thing, you have a background thread checking and, if necessary, reestablishing socket connections to remote server.

in case you also have control over your socket server development, i would recommend logging specifics from heartbeat messages. you could number them sequentially (or unixtime timestamp them) and then save to log, that way you can have an idea of how critical your problem is in real life. this might serve as a productive debugging tool.

like so:

A0001, A0002, A0003, B0001, A0004, B0002, B0003, A0005, C0001

where A, B, C are the connection ID's (and/or whatever other data you deem relevant, like originating IP, for example).

Upvotes: 1

user529758
user529758

Reputation:

Never perform networking operations on the main thread! Use separate background threads. Look for NSThread.

Upvotes: 6

Abizern
Abizern

Reputation: 150745

Have you tried using something like Reachability?

There is a sample project by Apple, but there are many updates of it on Github such as this one that works with ARC and GCD.

Basically, you monitor your network connection and handle events gracefully when it drops off.

Upvotes: 2

Related Questions