1

我正在尝试使用 GCDAsyncUdpSocket 来发现网络上的 DIAL 设备。我已成功使用 Netflix 的官方 C++ 客户端来发现设备,如此所述,但我想避免在我的 Swift 项目中使用 C++ 或 Objective-C++ 类。这是我的发现类,它报告正在创建和打开的套接字,但什么也没收到。是否有人精通 DIAL 足以看出我哪里出错了?

import Foundation
import CocoaAsyncSocket

class UDPListener: NSObject {

    var udpSocket: GCDAsyncUdpSocket?

    override init() {
        super.init()
        self.udpSocket = GCDAsyncUdpSocket(delegate: self, delegateQueue: dispatch_get_main_queue())
        self.udpSocket?.setIPv6Enabled(false)
        do {
            try self.udpSocket?.enableBroadcast(true)
            print("Broadcasting enabled.")
        } catch let error as NSError {
            print(error)
        }

        let interfaces = Helper.availableNetworkInterfaces()
        let sourceAddress = interfaces!.values.first as? NSData

        do {
            try self.udpSocket?.bindToAddress(sourceAddress)
            print("Bound to \(sourceAddress!))")
        } catch let error as NSError {
            print("Error binding address: \(error)")
            return
        }

        do {
            try self.udpSocket?.joinMulticastGroup("239.255.255.250", onInterface:  "en0")
            print("Joined multicast group.")
        } catch let error as NSError {
            print("Error joining group: \(error)")
            return
        }

        do {
            try self.udpSocket?.beginReceiving()
            print("Ready to receive data.")
        } catch let error as NSError {
            print("Error on trying to receive: \(error)")
            return
        }
        print("Socket created.")
    }

    func broadcast() {
        let data = "M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\nMAN: \"ssdp:discover\"\r\nMX: 3\r\nST: urn:dial-multiscreen-org:service:dial:1\r\nUSER-AGENT: iOS DIAL Client/1.0 UDPListener/1.0\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!
        self.udpSocket?.sendData(data, withTimeout: -1, tag: 0)
    }
}

extension UDPListener: GCDAsyncUdpSocketDelegate {

    func udpSocket(sock: GCDAsyncUdpSocket!, didReceiveData data: NSData!, fromAddress address: NSData!, withFilterContext filterContext: AnyObject!) {
        print("RECEIVED DATA: \(String(data: data, encoding: NSUTF8StringEncoding)!)\nFROM: \(Helper.constructURLsFromNSNetServiceAddresses([address])!)")
    }

    func udpSocket(sock: GCDAsyncUdpSocket!, didConnectToAddress address: NSData!) {
        print("connected")
    }

    func udpSocket(sock: GCDAsyncUdpSocket!, didNotConnect error: NSError!) {
        print("did not connect")
    }

    func udpSocket(sock: GCDAsyncUdpSocket!, didNotSendDataWithTag tag: Int, dueToError error: NSError!) {
        print("did not send data, error: \(error)")
    }

    func udpSocket(sock: GCDAsyncUdpSocket!, didSendDataWithTag tag: Int) {
        print("did send data")
    }

    func udpSocketDidClose(sock: GCDAsyncUdpSocket!, withError error: NSError!) {
        print("did close")
    }
}
4

0 回答 0