Swift-UDP接收和发送

时间:2018-11-02 01:55:33

标签: ios swift xcode udp esp8266

我正在尝试在iPhone应用程序和ESP8266之间发送和接收UDP数据包。我有几个ESP设备都可以正常通信,但是我一生无法为iOS创建任何可以看到或发送任何东西的东西。我尝试了SwiftSocket,CocoaAsyncSocket,UDPBroadcastConnection,Apple的新NetworkExtension / NetworkConnection库,但都无济于事。

目标设备的IP地址为192.168.4.1,我们使用的端口为4210。目标设备正在255.255.255.255上发送广播。我可以从我的Macbook中看到这些。

尝试从我的应用程序向任何IP发送或接收数据包均未成功。我已经尝试使用Mac应用商店中的应用PacketSender对其进行测试。任何人都可以推荐解决方案的实际功能示例吗?我现在不在乎上面使用的是哪个库,我只需要移动一些数据即可。

我确实确保了一个步骤:Xcode中的应用启用了网络扩展功能。

这是我的UDPBroadcastConnection尝试中的一个示例:

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

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

这里没有发送或接收任何东西。 使用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)
        }

一无所获。但是从准备状态变为准备状态。运行接收消息行,不打印任何内容。从不打印任何有关状态的进一步信息。试图通过按钮操作运行接收消息以尝试多次,但似乎仍然不想接收。

值得注意的是,该应用在模拟器上运行时能够接收自己的发送,但是似乎没有任何设备外连接(例如,与PacketSender的连接)

1 个答案:

答案 0 :(得分:0)

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)
    }
}