【问题标题】:NWConnection SSDP Discovery not receiving dataNWConnection SSDP 发现未接收数据
【发布时间】:2019-07-09 03:14:13
【问题描述】:

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

Network.framework 相对较新,没有太多信息。我在这里缺少什么?

SSDP Discovery 广播已发送,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()

【问题讨论】:

  • 感谢 NWconnection 示例,即使此示例不起作用。一旦我们习惯了 NWconnection 编程,它看起来会比 CFnetwork 更容易。

标签: ios swift xcode udp ssdp


【解决方案1】:

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

【讨论】:

【解决方案2】:

UDP 试试这个方法:

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

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

这是use here的一个很好的例子

我在使用 TCP 时遇到了相反的问题,并且正在使用 connection.receiveMessage(...),并且发生了同样的事情 -从未输入回调。我在Apple Forums 中发布了一个问题。原来TCP你只能使用:

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

苹果开发者技术支持专家eskimo answered it here

。 TCP 不是面向消息的协议,因此

receiveMessage(…)

没有任何意义。你想要的是

receive(minimumIncompleteLength:maximumLength:completion:)

话虽如此,用UDP试试connection.receiveMessage(…)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多