3

请参阅这篇文章,我在从 GCDAsyncSocket 接收数据时遇到一些问题,并且找不到有效的 Swift 示例。

import UIKit
import CocoaAsyncSocket


class DiscoveryViewControllerTest: UIViewController, GCDAsyncSocketDelegate{
    let host = "192.168.55.1"
    let port:UInt16 = 4000

    let cmdDeviceInformation = "?0600\r";
    let cmdDeviceIStandByeExit = "?060B\r";
    let cmdDeviceIStandByeEnter = "?060A\r";
    var mSocket: GCDAsyncSocket!

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print("Started wifi scanning!\n")

        mSocket = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.main)
        do {
            try mSocket.connect(toHost: host, onPort: port)
        } catch let error {
            print(error)
        }
        print("Connecting to instrument...!\n")
    }

    public func socket(_ socket: GCDAsyncSocket, didConnectToHost host: String, port p:UInt16){
        print("didConnectToHost!\n");

        let data = cmdDeviceIStandByeEnter.data(using: .utf8)
        print("TX: ", terminator: " ")
        print(data! as NSData)
        mSocket.write(data!, withTimeout:10, tag: 0)

        mSocket.readData(withTimeout: -1, tag: 0) //This line was missing!

    }

    public func socket(_ sock: GCDAsyncSocket, didWriteDataWithTag tag: Int) {
        print("didWriteData");
    }

    public func socket(_ sock: GCDAsyncSocket, didReceive trust: SecTrust, completionHandler: @escaping (Bool) -> Void) {
        print("didReceiveData")

        let rxData:Data = Data()
        mSocket.readData(to: rxData, withTimeout: 5, buffer: nil, bufferOffset: 0, tag: 0)
        print("RX: ", terminator: " ")
        print(rxData as NSData)
    }

    public func socket(_ sock: GCDAsyncSocket, didRead: Data, withTag tag:CLong){
        print("didRead!");
    }

    public func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) {
        print("didDisconnect!")
    }
}

连接和写入方法正在运行,但从未调用过“didReceive”方法。

控制台输出:

开始wifi扫描!

正在连接仪器...!

didConnectToHost!

TX:<3f303630 410d> didWriteData

编辑 我解决了我的问题并将问题代码更改为准备使用的示例。

4

1 回答 1

3

我找到了我的错。mSocket.write()线索是在函数调用后面启用读取socket didConnectToHost()。完整的函数如下所示:

public func socket(_ socket: GCDAsyncSocket, didConnectToHost host: String, port p:UInt16){
    print("didConnectToHost!\n");

    let data = cmdDeviceInformation.data(using: .utf8)
    print("TX: ", terminator: " ")
    print(data! as NSData)
    mSocket.write(data!, withTimeout:10, tag: 0)

    mSocket.readData(withTimeout: -1, tag: 0) // Add this line
}

顺便说一句:我编辑了我的问题,为每个人创建了一个随时可用的示例。

于 2018-04-12T10:32:34.157 回答