请参阅这篇文章,我在从 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
编辑 我解决了我的问题并将问题代码更改为准备使用的示例。