【问题标题】:Swift example for GCDAsyncSocketDelegateGCDAsyncSocketDelegate 的 Swift 示例
【发布时间】:2018-04-11 07:34:46
【问题描述】:

请参阅此post 我在从 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: didWriteData

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

【问题讨论】:

  • 调用“socketDidDisconnect”是否有错误?
  • @RJVKumar 不,不是。

标签: ios swift gcdasyncsocket gcdasyncudpsocket


【解决方案1】:

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

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
}

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

【讨论】:

    猜你喜欢
    • 2016-01-18
    • 2014-08-11
    • 1970-01-01
    • 2017-12-07
    • 2016-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多