繁体   English   中英

Swift - UDP 接收和发送

[英]Swift - UDP Receive & Send

我正在尝试在 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)")
        })

这里没有发送或接收任何内容。 使用网络连接:

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)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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