Background:
I'm using GCDAsyncSocket
on a project successfully with Swift 1.2 (via a bridging header).
The challenge right now is that it needs some sort of queue because the system it's connecting to can only process and return one command at a time.
So if it calls methods back to back, for example:
getSystemInfo()
getSystemStatus()
Only getSystemInfo()
is returned via the delegate callback because the system was busy processing it, however, the getSystemStatus()
was sent asynchronously
successfully but not processed by the controller. I'd like it to be able to make the calls back to back and have them queue and processed once the controller is done processing and returning back the previous response -- basically making the process synchronous.
Question:
As you can see below in the example code under, didConnectToHost
delegate callback, when it connects to the controller, it calls getSystemInfo()
then getSystemStatus()
back to back, it should call getSystemStatus()
after it gets the results from the system info.
I have been looking at NSCondition
, NSOperation
, even GCD, but I'm not sure what the most elegant way to approach this is. I don't want to put yet another queue processor in the mix since there already is a queue setup for the GCDAsyncSocket
. What is the best, most elegant way to handle this?
Pseudo Class Code:
public class SendNet: NSObject, GCDAsyncSocketDelegate {
var socket:GCDAsyncSocket! = nil
func setupConnection(){
var error : NSError?
if (socket == nil) {
socket = GCDAsyncSocket(delegate: self, delegateQueue: dispatch_get_main_queue())
} else {
socket.disconnect()
}
if (!socket.connectToHost(host, onPort: port, withTimeout: 5.0, error: &error)){
println("Error: \(error)")
} else {
println("Connecting...")
}
}
public func socket(socket : GCDAsyncSocket, didConnectToHost host:String, port p:UInt16) {
println("Connected to \(host) on port \(p).")
self.socket = socket
getSystemInfo()
getSystemStatus()
}
func send(msgBytes: [UInt8]) {
var msgData = NSData(bytes: msgBytes, length: msgBytes)
socket.writeData(msgData, withTimeout: -1.0, tag: 0)
socket.readDataWithTimeout(-1.0, tag: 0)
}
func getSystemInfo() {
var sendBytes:[UInt8] = [0x0, 0x1, 0x2, 0x3]
send(sendBytes)
}
func getSystemStatus() {
var sendBytes:[UInt8] = [0x4, 0x5, 0x6, 0x7]
send(sendBytes)
}
public func socket(socket : GCDAsyncSocket!, didReadData data:NSData!, withTag tag:Int){
var msgData = NSMutableData()
msgData.setData(data)
var msgType:UInt16 = 0
msgData.getBytes(&msgType, range: NSRange(location: 2,length: 1))
println(msgType)
}
}
Any suggestions would be great -- thanks!