簡體   English   中英

NWConnection SSDP 發現未接收數據

[英]NWConnection SSDP Discovery not receiving data

我正在嘗試進行 SSDP 發現廣播,但無法從 NWConnection.receive 獲取回復數據。

Network.framework 相對較新,沒有太多信息。 我在這里缺少什么?

發送了 SSDP 發現廣播並且 UPnP 設備進行了回復。 (以下Wireshark截圖) 在此處輸入圖片說明

    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

使用UDP試試這個方法:

connection.receiveMessage { (data, context, isComplete, error) in

    print(data ?? "", context ?? "", isComplete, error ?? "")
}

這是它在此處使用的一個很好的例子

我在TCP遇到了相反的問題,正在使用connection.receiveMessage(...)並且發生了同樣的事情 -從未輸入過回調 我在Apple 論壇上發布了一個問題。 事實證明,對於TCP您只能使用:

connection.receive(minimumIncompleteLength: 1, maximumLength: 65535) { data, context, isComplete, error in
    
    print(data ?? "", context ?? "", isComplete, error ?? "")
}

一位名叫愛斯基摩的 Apple 開發人員技術支持專家在這里回答了這個問題

. TCP 不是面向消息的協議,因此

receiveMessage(…)

沒有任何意義。 你想要的是

receive(minimumIncompleteLength:maximumLength:completion:)

話雖如此,使用UDP嘗試connection.receiveMessage(…)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM