具有同步和异步模式的macOS swift4 GCDAsyncSocket

时间:2019-02-22 09:38:54

标签: swift macos sockets cocoa

我将使用GCDAsyncSocket实现同步或异步swift套接字客户端。

以下是通过GCDAsyncSocket实现异步模式的示例。

class TestAsyncSocket: NSObject, GCDAsyncSocketDelegate{
    func startSocket(){
        mAsyncSocket = GCDAsyncSocket.init(delegate: self, delegateQueue: DispatchQueue.main)
        do {
            try mAsyncSocket?.connect(toHost: hostURL, onPort: port)
        } catch {
            print("Failed to connect")
        }
    }

    func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) {
        print("DidConnectToHost: %@  port: %@", host, port)
    }

    func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) {
        print("DisConnect to host: %@", err ?? hostURL)
    }

    func sendData(cmdJson: Data) {
        mAsyncSocket.write(cmdJson, withTimeout: -1, tag: 0)
        mAsyncSocket.readData(withTimeout: -1, tag: 0)
    }

    func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) {
        let dataString = String.init(data: data, encoding: String.Encoding.utf8)
        print("Received Data on Socket =====>", dataString ?? "")
    }

某些套接字实例应以同步模式工作,而另一些则应为异步模式。

您能建议我如何同时实现同步和异步模式吗?

0 个答案:

没有答案