使用
NWConnection.recieve()
通过UDP套接字接收数据的好方法是什么?我能想到的只是递归函数,但这会很快耗尽内存并使应用程序崩溃。
附注
NWConnection.recieveMessage()
与 NWConnection.recieve()
相同,但没有限制范围
文档说
Schedules single 接收完整消息的完成处理程序,而不是字节范围。
这是否意味着如果我运行一次,它将等到有东西要听,然后运行完成处理程序?我尝试过这个,但它不起作用。我在
listen()
尝试这个。
class UDPConnection {
var connection: NWConnection?
var response: Data
init() {
connection = NWConnection(host: NWEndpoint.Host("192.168.0.32"), port: NWEndpoint.Port(rawValue: 32)!, using: .udp)
response = Data()
}
func begin() {
guard let connection = connection else {
print("Connection not initialized.")
return
}
connection.start(queue: .global())
print("Connection started.")
self.listen()
}
func sendData(_ data: Data) {
//connection = NWConnection(host: NWEndpoint.Host("192.168.0.32"), port: NWEndpoint.Port(rawValue: 32)!, using: .udp)
//self.begin()
guard let connection = connection else {
print("Connection not initialized.")
return
}
connection.start(queue: .global())
connection.send(content: data, completion: .contentProcessed { sendError in
if let error = sendError {
print("Failed to send data: \(error)")
} else {
print("Data sent successfully")
}
})
// DispatchQueue.global().asyncAfter(deadline: .now() + 1.0) {
// self.closeConnection()
// print("Connection closed via `DispatchQueue`")
// }
}
func listen() {
guard let connection = connection else {
print("Connection not initialized.")
return
}
if connection.state == .ready {
connection.receiveMessage { (data, _, _, error) in
print("here2")
if let error = error {
print("Error receiving data: \(error)")
return
}
print("Data received successfully")
self.response = data ?? Data([0x65])
print(self.response)
self.listen()
}
print("here")
} else {
print("Connection not ready to receive data.")
DispatchQueue.global().asyncAfter(deadline: .now() + 0.1) {self.listen()}
}
}
func closeConnection() {
guard let connection = connection else {
print("Connection not initialized.")
return
}
connection.cancel()
print("Connection closed.")
}
}
此外,如果有帮助,我会在控制台中收到一些警告:
Error creating the CFMessagePort needed to communicate with PPT.
一开始,
nw_connection_set_queue_block_invoke [C1] Error in client: nw_connection_set_queue called after nw_connection_start
在我收到第一条数据之前,并且
nw_connection_set_queue_block_invoke [C1] Error in client: nw_connection_set_queue called after nw_connection_start, backtrace limit exceeded
在每条正在进行的数据之前。