问题
I send UDP packets to a wifi module and receive them and i monitor them in serial port monitor successfully but unable to receive them in iOS app.
I'm using Network Framework both for connecting and receive. The connection part works perfectly but when i set a listener to the port, and try to get rsponse the receiveMessage
doesn't get called although i see outpackets that module sends.
class func connect()
{
connection = NWConnection(host: hostUDP, port: portUDP, using: .udp)
connection?.stateUpdateHandler =
{
(newState) in switch (newState)
{
case .ready:
//The connection is established and ready to send and recieve data.
print("ready")
self.sendPaket(self.sendingPacket)
self.receive()
case .setup:
//The connection has been initialized but not started
print("setup")
case .cancelled:
//The connection has been cancelled
print("cancelled")
case .preparing:
//The connection in the process of being established
print("Preparing")
default:
//The connection has disconnected or encountered an error
print("waiting or failed")
}
}
connection?.start(queue: Protocols.sendQueue)
}
class func sendPaket(_ packet:String)
{
let packet = dataWithHexString(hex: sendingPacket)
print("converted version to byte is :\(packet)")
connection?.send(content: packet, completion: NWConnection.SendCompletion.contentProcessed((
{
(NWError) in
print("error in sending packet : \(String(describing:NWError))")
})))
}
class func receive()
{
connection?.receiveMessage(completion:
{
(data, context, isComplete, error) in
print("Got it")
if data != nil
{
print("context:\n")
print((context?.protocolMetadata)!)
Protocols.receivedPacket = data?.dataToHexEncodedString()
print("received packet:\n")
print(Protocols.receivedPacket!)
let rec = Test()
rec.label.text = Protocols.receivedPacket
}
print("receive error: \(String(describing: error))")
})
}
来源:https://stackoverflow.com/questions/58401093/swift-receiving-udp-packets-from-server-on-serial-port-monitor-but-not-in-ios-a