我正在尝试做一个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()发布于 2019-02-15 21:15:05
原来Network.framework还不支持UDP广播(2019年2月) https://forums.developer.apple.com/message/316357#316357
发布于 2020-12-16 04:51:37
使用UDP,可以尝试以下方法:
connection.receiveMessage { (data, context, isComplete, error) in
print(data ?? "", context ?? "", isComplete, error ?? "")
}下面是在这里使用中的一个很好的例子
我在使用TCP时遇到了相反的问题,并且正在使用connection.receiveMessage(...),同样的事情也在发生----回调从未进入。我在苹果论坛上发布了一个问题。结果发现,在TCP中只能使用:
connection.receive(minimumIncompleteLength: 1, maximumLength: 65535) { data, context, isComplete, error in
print(data ?? "", context ?? "", isComplete, error ?? "")
}一位名为爱斯基摩人在这里回答的苹果开发者技术支持专家
。TCP不是一个面向消息的协议,因此。
receiveMessage(…)没有任何意义。你想要的是
receive(minimumIncompleteLength:maximumLength:completion:)话虽如此,用UDP试试connection.receiveMessage(…)
https://stackoverflow.com/questions/54701499
复制相似问题