简体   繁体   中英

Swift - UDP Receive & Send

I am trying to send and receive UDP packets between an iPhone app and an ESP8266. I have several ESP devices all communicating just fine, but I can not for the life of me create anything for iOS that will see or send anything. I have tried SwiftSocket, CocoaAsyncSocket, UDPBroadcastConnection, Apple's new NetworkExtension/NetworkConnection library, all to no avail.

The target device IP address is 192.168.4.1, and the port we are using is 4210. The target device is sending out broadcasts on 255.255.255.255. I can see these from my macbook.

Trying to send or receive packets to any IP from my app has been unsuccessful. I have tried testing it with the app PacketSender from the mac app store. Can anyone recommend an actual functional working example of a solution? I don't care at this point which of the above libraries is the one being used, I just need to move some data.

One step I did ensure: The app in Xcode has the Network Extension capabilities enabled.

Here is an example from my UDPBroadcastConnection attempt:

// in viewDidLoad()...
// ...
//broadcastConnection declared globally

broadcastConnection = UDPBroadcastConnection(port: 4210, handler: { (ip, port, response) in
            print("Received from \(ip):\(port):\n\n\(response)")
        })

Nothing sent or received here. With NetworkConnection:

connection = NWConnection(host: "192.168.4.1", port: 4210, using: .udp)

        connection!.stateUpdateHandler = { (newState) in
            switch (newState) {
            case .ready:
                print("ready")
            case .setup:
                print("setup")
            case .cancelled:
                print("cancelled")
            case .preparing:
                print("Preparing")
            default:
                print("waiting or failed")
                break
            }
        }
        connection!.start(queue: .global())

        connection!.receiveMessage { (data, context, isComplete, error) in
            print("Got it")
            print(data)
        }

Never receives anything. Does however go from preparing to ready state. Runs the receive message line, doesn't print anything. Never prints any further information about state. Tried to run the receive message off of a button action to try more than once, still does not seem to want to receive.

It may be worth noting that the app is able to receive its own sends when running on the simulator, but there doesn't appear to be any connection out of the device (to/from PacketSender, for example)

import UIKit
import Network

class ViewController: UIViewController {
     
    var connection: NWConnection?
    var hostUDP: NWEndpoint.Host = "192.168.4.1"
    var portUDP: NWEndpoint.Port = 4210
    
    @IBOutlet weak var lableRedy: UILabel!
    @IBOutlet weak var lableReceive: UILabel!
    @IBOutlet weak var lableMessege: UILabel!

    override func viewDidLoad() {
     
    }
    
    //MARK:- UDP
      func connectToUDP(_ hostUDP: NWEndpoint.Host, _ portUDP: NWEndpoint.Port) {
          // Transmited message:
       
        let messageToUDP = "7773010509060602040701000001010d0a"
          self.connection = NWConnection(host: hostUDP, port: portUDP, using: .udp)
          self.connection?.stateUpdateHandler = { (newState) in
              print("This is stateUpdateHandler:")
              switch (newState) {
                  case .ready:
                      print("State: Ready\n")
                      self.sendUDP(messageToUDP)
                      self.receiveUDP()
                  case .setup:
                      print("State: Setup\n")
                  case .cancelled:
                      print("State: Cancelled\n")
                  case .preparing:
                      print("State: Preparing\n")
                  default:
                      print("ERROR! State not defined!\n")
              }
          }

          self.connection?.start(queue: .global())
      }

      func sendUDP(_ content: Data) {
          self.connection?.send(content: content, completion: NWConnection.SendCompletion.contentProcessed(({ (NWError) in
              if (NWError == nil) {
                  print("Data was sent to UDP")
              } else {
                  print("ERROR! Error when data (Type: Data) sending. NWError: \n \(NWError!)")
              }
          })))
      }

      func sendUDP(_ content: String) {
        let contentToSendUDP = content.data(using: String.Encoding.utf8)
          self.connection?.send(content: contentToSendUDP, completion: NWConnection.SendCompletion.contentProcessed(({ (NWError) in
              if (NWError == nil) {
                  print("Data was sent to UDP")
                 DispatchQueue.main.async { self.lableRedy.text = "Data was sent to UDP" }
              } else {
                  print("ERROR! Error when data (Type: Data) sending. NWError: \n \(NWError!)")
              }
          })))
      }

      func receiveUDP() {
          self.connection?.receiveMessage { (data, context, isComplete, error) in
            if (isComplete) {
                  print("Receive is complete")
                 DispatchQueue.main.async { self.lableReceive.text = "Receive is complete" }
                  if (data != nil) {
                      let backToString = String(decoding: data!, as: UTF8.self)
                      print("Received message: \(backToString)")
                    DispatchQueue.main.async { self.lableMessege.text = backToString }
                    
                  } else {
                      print("Data == nil")
                  }
              }
          }
      }
    

    @IBAction func tappedSend(_ sender: Any) {
       connectToUDP(hostUDP,portUDP)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM