iOS 应用未接收到 UDP 广播数据报

iOS app not receiving UDP broadcast datagrams

我是 iOS 的新手,我正在尝试让我的应用程序侦听端口 (10704) 上的所有 UDP 广播。我已经在 Android 版本(发送和接收)上实现了这个,所以我 100% 确定正在发送网络请求。我得到输出,那个设置发生了,但没有别的。我从来没有在 iOS 端收到任何传入网络数据的迹象。到目前为止,我的代码(class 是在应用程序 class 的 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))");
    }
    
}

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

编辑:添加了我的创建方式 InSocket

    var sckt: InSocket!

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

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

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