【问题标题】:iOS app not receiving UDP broadcast datagramsiOS 应用程序未收到 UDP 广播数据报
【发布时间】:2020-06-30 08:58:29
【问题描述】:

我对 iOS 还很陌生,我正在尝试让我的应用程序监听端口 (10704) 上的所有 UDP 广播。我已经在 Android 版本(发送和接收)上实现了这个功能,所以我 100% 确定正在发送网络请求。我得到输出,设置发生了,但没有别的。我从来没有在 iOS 端收到任何传入网络数据的迹象。到目前为止我的代码(在 Application 类的 didFinishLaunchingWithOptions 中创建的类:

import CocoaAsyncSocket

class InSocket: NSObject, GCDAsyncUdpSocketDelegate {


   let PORT:UInt16 = 10704
   var socket:GCDAsyncUdpSocket!

   override init(){
       super.init()
       setupConnection()
   }

   func setupConnection(){
        socket = GCDAsyncUdpSocket(delegate: self, delegateQueue: DispatchQueue.global())
        try! socket.bind(toPort: PORT)
        try! socket.enableBroadcast(true)
        try! socket.beginReceiving()
        print("after setup!")
   }
    
    func udpSocket(_ sock: GCDAsyncUdpSocket, didNotConnect error: Error?) {
        print("didNotConnect!")
    }
    
    func udpSocket(_ sock: GCDAsyncUdpSocket, didSendDataWithTag tag: Int) {
        print("didSendDataWithTag")
    }
    
    func udpSocket(_ sock: GCDAsyncUdpSocket, didConnectToAddress address: Data) {
        print("didConnectToAddress")
    }
    
    func udpSocket(_ sock: GCDAsyncUdpSocket, didNotSendDataWithTag tag: Int, dueToError error: Error?) {
        print("didNotSendDataWithTag")
    }
    
    func udpSocketDidClose(_ sock: GCDAsyncUdpSocket, withError error: Error?) {
        print("udpSocketDidClose")
    }

    func udpSocket(_ sock: GCDAsyncUdpSocket, didReceive data: Data, fromAddress address: Data, withFilterContext filterContext: Any?) {
        print("incoming message1: \(String(describing: data))");
        
    }
    
    func udpSocket(sock: GCDAsyncUdpSocket!, didReceiveData data: NSData!, fromAddress address: NSData!,      withFilterContext filterContext: AnyObject!) {
        print("incoming message2: \(String(describing: data))");
    }
    
}

最后 2 个类似,因为其中 1 个是从示例代码中复制的(可能是过时的签名),另一个是由 xcode 自动完成生成的。

编辑:添加了我如何创建InSocket

    var sckt: InSocket!

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        sckt = InSocket()        
        return true
    }

【问题讨论】:

  • 展示如何创建InSocket的实例
  • 我将其添加到问题中。
  • 您可以尝试使用主队列为您的delegateQueue
  • 我做到了,而且成功了!很奇怪,我尝试了很多东西,甚至改变了 delegateQueue。你能详细回答吗?我很乐意接受。

标签: ios swift udp broadcast


【解决方案1】:

并非所有队列都与RunLoop 关联。如果没有与RunLoop 关联,队列将无法执行异步工作。

如果您将委托队列移动到主队列,您将收到委托回调,因为主队列被安排到主运行循环中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-28
    • 2012-03-10
    • 1970-01-01
    相关资源
    最近更新 更多