简体   繁体   English

Swift - UDP 接收和发送

[英]Swift - UDP Receive & Send

I am trying to send and receive UDP packets between an iPhone app and an ESP8266.我正在尝试在 iPhone 应用程序和 ESP8266 之间发送和接收 UDP 数据包。 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.我有几个 ESP 设备都可以正常通信,但是我一生都无法为 iOS 创建任何可以查看或发送任何内容的内容。 I have tried SwiftSocket, CocoaAsyncSocket, UDPBroadcastConnection, Apple's new NetworkExtension/NetworkConnection library, all to no avail.我尝试过 SwiftSocket、CocoaAsyncSocket、UDPBroadcastConnection、Apple 的新 NetworkExtension/NetworkConnection 库,但都无济于事。

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.目标设备IP地址是192.168.4.1,我们使用的端口是4210。目标设备在255.255.255.255上发送广播。 I can see these from my macbook.我可以从我的 macbook 上看到这些。

Trying to send or receive packets to any IP from my app has been unsuccessful.尝试从我的应用程序向任何 IP 发送或接收数据包均未成功。 I have tried testing it with the app PacketSender from the mac app store.我曾尝试使用 mac 应用商店中的应用 PacketSender 对其进行测试。 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.我确保的一个步骤是:Xcode 中的应用程序启用了网络扩展功能。

Here is an example from my UDPBroadcastConnection attempt:这是我的 UDPBroadcastConnection 尝试中的一个示例:

// 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)可能值得注意的是,应用程序在模拟器上运行时能够接收自己的发送,但似乎没有任何设备外的连接(例如到/来自 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