Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone Socket fails after a large number of data transfers

Tags:

iphone

sockets

I've got an interesting issue with my socket test application.

I've set up a listening socket with an AcceptCallback function. I've connected to the listening socket using :

CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, 
                                   (CFStringRef) self.clientService.hostName, 
                                   self.clientService.port, 
                                   &myReadStream,
                                   &myWriteStream);

and I've send data back to the listening socket the myReadStream and myWriteStream, both of which I've cast to their NSStream equivalents.

The problem occurs after sending many separate packets of data. The size of the packets do not matter, it's the number of packets (or the number of CFStreamCreatePairWithSocketToHost creations) that seems to introduce the error.

After I send tons of packets (maybe around 100 or 200), when I try to send data over the NSOutputStream I get an error in the NSStreamEvent callback:

Operation could not be completed. (NSUnknownErrorDomain error 8.)

Then, if I try to create a new service and publish it on the network I get an error when I try to resolve the new address. It gives me an error code of 10 in the NSNetService:didNotResolve delegate method (also, the error description is blank here).

It's almost as if the listening socket is "full" but it seems to think it's functioning fine because when I check CFSocketIsValid it returns true.

I'm stumped and have spent several hours trying to debug the situation... Any thoughts anybody? Thanks.

like image 642
devinkb Avatar asked Nov 06 '22 16:11

devinkb


1 Answers

Alright, I figured out the issue.

When connecting to a socket and initializing a read and write stream, as with the following:

CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (CFStringRef) self.clientService.hostName, self.clientService.port, &myInputStream, &myWriteStream);

you need to make sure you set the following variable so that the lower level BSD stream closes when you close the CFStream or NSStream (in my case I cast the CFStream to an NSStream type):

CFReadStreamSetProperty(myReadStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
CFWriteStreamSetProperty(myWriteStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);

If you don't set this property the BSD stream never actually closes and you hit some sort of max number of socket connections - not sure exactly what the problem is.

like image 98
devinkb Avatar answered Nov 12 '22 15:11

devinkb