我正在尝试进行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()
答案 0 :(得分:1)
结果证明 Network.framework 目前不支持 UDP广播(2019年2月) https://forums.developer.apple.com/message/316357#316357
答案 1 :(得分:0)
使用UDP
尝试以下方法:
connection.receiveMessage { (data, context, isComplete, error) in
print(data ?? "", context ?? "", isComplete, error ?? "")
}
中的一个很好的例子
我在TCP
上遇到了相反的问题,并且正在使用connection.receiveMessage(...)
,并且发生了相同的事情-从未输入回调。我在Apple Forums发表了一个问题。事实证明,TCP
您只能使用:
connection.receive(minimumIncompleteLength: 1, maximumLength: 65535) { data, context, isComplete, error in
print(data ?? "", context ?? "", isComplete, error ?? "")
}
Apple开发人员技术支持专家,名为eskimo answered it here:
。 TCP不是面向消息的协议,因此
receiveMessage(…)
没有任何意义。您想要的是
receive(minimumIncompleteLength:maximumLength:completion:)
话虽如此,请UDP
试试connection.receiveMessage(…)