Search code examples
objective-csocketsadhoc

Socket check TCP/IP connection exists and shorten timeout


I am trying to connect my iOS application to a printer on a adhoc network, I need to check the connection is open and valid before sending anything to the printer, How can I achieve this? currently I am doing the following CFReadStreamRef readStream; CFWriteStreamRef writeStream;

readStream = NULL;
writeStream = NULL;

CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)IPADDRESS, NUM_PORT,NULL ,&writeStream );

if(writeStream)
{
    //inputStream = (__bridge NSInputStream *)readStream;
    oStream = (__bridge NSOutputStream *)writeStream;

    //[iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    //[iStream setDelegate:delegate];
    [oStream setDelegate:delegate];
    //[iStream open];
    [oStream open];
}

and

   int bytesWritten;
   int bytesTotal = [data length];

   bytesWritten = [oStream write:[data bytes] maxLength: bytesTotal];
   NSLog(@"Bytes Written To Printer : %d",bytesWritten);

but it is always going in and writeStream is never null so I am unable to stop it trying to push data to the socket.

~Edit - Maybe I'm best rephrasing my question, How can I stop it from hanging for 30+ seconds until it realises there is no connection?


Solution

  • I need to check the connection is open and valid before sending anything to the printer, How can I achieve this?

    By sending something to the printer. The only way to detect a connection problem in TCP is to do some I/O with it.