lmirosevic
lmirosevic

Reputation: 16317

What can cause a CFSocket to close itself?

I have a class method which requires an underlying CFSocket, and this method gets called very often so it's too expensive to create and destroy a new socket each time the method runs. So instead I've created a static instance of a CFSocketRef so I can share a single socket between method calls:

+(void)myStaticMethod {
    static CFSocketRef udpSocket;

    @synchronized(self) {
        if (!udpSocket) {
            udpSocket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_DGRAM, IPPROTO_UDP, 0, NULL, NULL);
            int yes = 1;
            setsockopt(CFSocketGetNative(udpSocket), SOL_SOCKET, SO_NOSIGPIPE, (void *)&yes, sizeof(yes));
        }
    }

    //method body
}

I have two questions:

  1. Do I have to worry about destroying (invalidating) the socket when the app will terminate, or does it close itself?
  2. Which events might cause the socket to close itself and how would you prevent potentially writing to a bad CFSocketRef?

Upvotes: 0

Views: 460

Answers (1)

Martin R
Martin R

Reputation: 540075

If an app really terminates then all resources, including sockets, are released. But normally apps don't terminate but go into the background and in that case the socket can become invalid. This is described quite well in Technical Note TN2277. See in particular the section "Data Socket".

Since the creation of an UDP socket is a simple operation, the following advice from TN2277 would apply to your code:

If reopening your data socket is simple, cheap, and has no user visible consequences, the best approach is to close the socket when the app goes into the background, and reopen it when it comes back into the foreground. This makes your life very simple; in fact, if you do this, you can ignore the rest of this section entirely!

Upvotes: 1

Related Questions