📅  最后修改于: 2022-03-11 14:59:49.134000             🧑  作者: Mango
var connection: NWConnection?
func someFunc() {
self.connection = NWConnection(host: "255.255.255.255", port: 9093, using: .udp)
self.connection?.stateUpdateHandler = { (newState) in
switch (newState) {
case .ready:
print("ready")
self.send()
self.receive()
case .setup:
print("setup")
case .cancelled:
print("cancelled")
case .preparing:
print("Preparing")
default:
print("waiting or failed")
}
}
self.connection?.start(queue: .global())
}
func send() {
self.connection?.send(content: "Test message".data(using: String.Encoding.utf8), completion: NWConnection.SendCompletion.contentProcessed(({ (NWError) in
print(NWError)
})))
}
func receive() {
self.connection?.receiveMessage { (data, context, isComplete, error) in
print("Got it")
print(data)
}
}