0

I have an app which listens for a socket connection, and then uses DispatchSource.makeReadSource to read from the socket. This bit is working great:

let mySocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)
// bind(...)
listen(newSocket, 1)

let clientSocket = accept(...)

let clientListener = DispatchSource.makeReadSource(
    fileDescriptor: clientSocket, 
    queue: DispatchQueue.main)
clientListener.setEventHandler {
    // Called when data is available, and I can read it without problem
}

My problem is while the dispatch source is waiting for data from the client, if I deploy my app (or stop my app) using Xcode, somehow the socket remains open and I cannot setup my socket again. When I call bind it returns -1

I have to restart my device for the socket to be released again

I've tried cleaning up my sockets when the app is closed, but I can't seem to detect when Xcode kills my app:

  • applicationWillTerminate is not called in my app delegate
  • deinit isn't called in any of my classes
  • none of the life cycle methods are called in my view controller

I'm not sure how the socket is remaining open as I would assume iOS would kill of all the resources when it killed the app

Is there a way to stop the dispatcher from holding on to the socket?

MrK
  • 652
  • 1
  • 5
  • 17
  • 1
    Do you set the SO_REUSEADDR socket option? Compare https://hea-www.harvard.edu/~fine/Tech/addrinuse.html or https://stackoverflow.com/q/15198834/1187415. – Martin R Aug 13 '19 at 20:04
  • I was just trying this out after spotting it as the answer in the "Related questions" section. It seems to be working now! If you provide your comment as an answer I can mark it – MrK Aug 13 '19 at 20:11
  • I think we can close the question as a duplicate of that Q&A. – Martin R Aug 13 '19 at 20:12

0 Answers0