Swift: Receiving UDP packets from server on serial port monitor but not in ios app

一曲冷凌霜 提交于 2020-01-03 06:19:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!