CocoaAsyncSocket:调用dispatch_sync(socketQueue,block)时创建iOS UDP套接字时出错

时间:2017-08-14 14:50:14

标签: ios swift sockets udp cocoaasyncsocket

我想写一个 iOS Swift app ,它可以在本地连接到UDP服务器。

以下是我使用名为 CocoaAsyncSocket 的库编写的代码,但是当我运行它时会崩溃。

我在Apple中没有找到任何类似的高级API。我发现的唯一一件事是documentation,它向我们建议了更高级别的API。

你能指出我更好的图书馆或解决我得到的错误吗?

import UIKit
import CocoaAsyncSocket

class OutputSocket: NSObject, GCDAsyncUdpSocketDelegate {

    var serverIP = "127.0.0.1"
    var port:UInt16 = 10000
    var socket:GCDAsyncUdpSocket!

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

    func setupConnection(){
        socket = GCDAsyncUdpSocket(delegate: self, delegateQueue: DispatchQueue.main)

        do {
            try socket.bind(toPort: self.port)
        }
        catch {
             print("binding error: ", error.localizedDescription)
        }

        let addressData = serverIP.data(using: String.Encoding.utf8)

        do {
            try socket.connect(toAddress: addressData!)}
        catch
        {
            print("connecting error: ", error.localizedDescription)
        }

        do {
            try socket.beginReceiving()
        }
        catch {
            print("connecting error: ", error.localizedDescription)
        }
    }

    func send(message:String){
        let data = message.data(using: String.Encoding.utf8)
        let addressData = serverIP.data(using: String.Encoding.utf8)
        socket.send(data!, toAddress: addressData!, withTimeout: 2, tag: 0)
    }

    func udpSocket(_ sock: GCDAsyncUdpSocket, didConnectToAddress address: Data) {
        print("didConnectToAddress");
    }

    func udpSocket(_ sock: GCDAsyncUdpSocket, didNotConnect error: Error?) {
        print("didNotConnect \(error)")
    }

    func udpSocket(_ sock: GCDAsyncUdpSocket, didSendDataWithTag tag: Int) {
        print("didSendDataWithTag")
    }

    func udpSocket(_ sock: GCDAsyncUdpSocket!, didNotSendDataWithTag tag: Int, dueToError error: Error!) {
        print("didNotSendDataWithTag")
    }
}

错误说明:

当我运行它时,它崩溃了:

enter image description here

编辑:

我已从等式中删除了IP地址,现在,当我运行以下代码时,我得到“didNotSendDataWithTag”:

    let data = message.data(using: String.Encoding.utf8)
    socket.send(data!, withTimeout: 2, tag: 0)

知道为什么吗?

0 个答案:

没有答案