我正在尝试进行SSDP发现广播,并且无法从NWConnection.receive获取答复数据。

Network.framework相对较新,并且那里没有很多信息。我在这里想念的是什么?

发送了SSDP Discovery广播,并回复了UPnP设备。 (下面的Wireshark屏幕截图)
ios - NWConnection SSDP发现未接收到数据-LMLPHP

    import Foundation
    import Network

    let connection = NWConnection(host: "239.255.255.250", port: 1_900, using: .udp)

    func sendBroadcast() {
        let message = """
            M-SEARCH * HTTP/1.1
            ST: ssdp:all
            HOST: 239.255.255.250:1900
            MAN: ssdp:discover
            MX: 1
            """.data(using: .utf8)

        connection.send(content: message, completion: .contentProcessed { error in
                if let error = error {
                    print("Send Error: \(error)")
                } else {
                    print("Broadcast sent")
                }
            }
        )
    }

    connection.stateUpdateHandler = { newState in
        switch newState {
        case .setup:
            print("Connection: Setup")
        case .preparing:
             print("Connection: Preparing")
        case .waiting:
            print("Connection: Waiting")
        case .ready:
            print("Connection: Ready")
            sendBroadcast()
        case .failed:
            print("Connection: Failed")
        case .cancelled:
            print("Connection: Cancelled")
        }
    }

    connection.receive(minimumIncompleteLength: 2, maximumLength: 4_096) { data, context, isComplete, error in
        /// This is never executed
        ///
        print(data ?? "", context ?? "", isComplete, error ?? "")
    }

    connection.viabilityUpdateHandler = { update in
        print(update)
    }

    connection.betterPathUpdateHandler = { path in
        print(path)
    }

    connection.start(queue: .main)

    RunLoop.main.run()

最佳答案

原来 Network.framework 尚不支持 UDP广播(2019年2月)
https://forums.developer.apple.com/message/316357#316357

关于ios - NWConnection SSDP发现未接收到数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54701499/

10-11 21:22