我将 UDP 数据包发送到 wifi 模块并接收它们,我在串行端口监视器中成功监控它们,但无法在 iOS 应用程序中接收它们。
我正在使用网络框架进行连接和接收。连接部分工作得很好,但是当我为端口设置一个侦听器并尝试获取 rsponse 时,receiveMessage
尽管我看到模块发送的输出包,但它并没有被调用。
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))")
})
}