Have each peer decide on its own unique ID.
When a client connects to a server, the first message it sends across that connection contains its unique ID.
The server then responds with its own unique ID.
If either end discovers that a connection with that unique ID pair already exists, it drops one of the connections. As long as they both agree to drop the same connection, everything will be fine. A good strategy here is to drop the one with the lesser ID.
Code Block connection.stateUpdateHandler = { [weak self](nwConnectionState) in switch nwConnectionState { case .preparing: print("Connection preparing") // it's stuck here // ... } }
Here is how I use the custom param (rest of setup is in this question):
Code Block var listener: NWListener? init () { do { let uid = UUID().uuidString let parameters = NWParameters(uid: uid) listener = try NWListener(using: parameters) listener?.service = NWListener.Service(name: "MyName", type: "_myApp._tcp") startListening() } catch { } }
I'm using UUID().uuidString to create the uid just so that I can attempt what @eskimo proposed in step 2 and step 4. Once the user kills the app and opens it again a new uid will be generated every time they try to connect with other devices. Because of this I don't need the uid to be secure. The Apple TikTokToe tls code seemed like overkill for my situation so I removed all of the encryption features that they used.
How do I add the uid string to the NWProtocolTLS.Options()?
Code Block extension NWParameters { convenience init(uid: String) { let tcpOptions = NWProtocolTCP.Options() tcpOptions.enableKeepalive = true tcpOptions.keepaliveIdle = 2 self.init(tls: NWParameters.tlsOptions(uid: uid), tcp: tcpOptions) } private static func tlsOptions(uid: String) -> NWProtocolTLS.Options { let tlsOptions = NWProtocolTLS.Options() return tlsOptions } }
It should be noted that outside of the problems inside the link, the problem from this question is avoided and .ready is called when I use the normal initializer:
Code Block let tcpOptions = NWProtocolTCP.Options() tcpOptions.enableKeepalive = true tcpOptions.keepaliveIdle = 2 let parameters = NWParameters(tls: nil, tcp: tcpOptions) parameters.includePeerToPeer = true