NWListener stops receiving incoming connections after a minute

I am listening to DLNA notifications over TCP and for about a minute, my NWListener instance keeps receiving new notifications but after about a minute, it stops getting the notifications. NWListener is still alive at that point and the DLNA subscription is valid as well. No such issues when listening using GCDWebserver. Am I missing something obvious with NWListener?

Replies

after about a minute, it stops getting the notifications.

What platform are you testing this on?

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

iOS (16/17) and macCatalyst, same behaviour in each case.

I can’t think of anything that would cause a TCP NWListener to stop listening after 60 seconds on a Mac. I tested this here in my office and didn’t see the behaviour you’re reporting. Specifically:

  1. Using Xcode 14.3 on macOS 13.4.1 (hey, I’m up-to-date for once!) I created a new test project from the macOS > App template.

  2. In Signing & Capabilities, I disabled the App Sandbox.

  3. I modified applicationDidFinishLaunching(_:) as follows:

    var listener: NWListener!
    
    func applicationDidFinishLaunching(_ aNotification: Notification) {
        let listener = try! NWListener(using: .tcp, on: 12345)
        listener.stateUpdateHandler = { newState in
            print("\(Date.now): did change state, new: \(newState)")
        }
        listener.newConnectionHandler = { newConnection in
            print("\(Date.now): did receive connection, dropping")
        }
        listener.start(queue: .main)
        self.listener = listener
    }
    
  4. I ran the app, resulting in this output:

    2023-06-30 08:34:28 +0000: did change state, new: ready
    
  5. In Terminal, I connected to my app’s server:

    % nc localhost 12345
    

    resulting in this output:

    2023-06-30 08:34:32 +0000: did receive connection, dropping
    
  6. I waited two minutes and repeated the previous step; here’s what I got:

    2023-06-30 08:36:45 +0000: did receive connection, dropping
    

I’m not sure why you’re seeing this problem but my advice is:

  • Repeat the above process, just to rule out environmental issues.

  • Integrate my listener code into your real app and see if it has the problem there.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

  • All works as expected when using the nc command, however when listening to the DLNA notifications NWListener still stops receiving them after a minute or so. No such issues with a GCDWebserver based listener so I have to use that for now.

Add a Comment