Search code examples
queuedelaycocoaasyncsocketgcdasyncsocket

CocoaAsyncSocket / GCDAsyncSocket add a delay between writes on the queue


I have the following function:

if (socket==nil)
  socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
if (elBuffer==nil) 
  elBuffer = [[NSMutableData alloc] init];
}

if ([socket isDisconnected]) {
  NSError *err = nil;
  [socket connectToHost:elControlador.ip onPort:9761 error:&err]
}

[socket writeData:@"A01" withTimeout:30 tag:1];
[socket writeData:@"A02" withTimeout:30 tag:1];
[socket writeData:@"A03" withTimeout:30 tag:1];
[socket writeData:@"A04" withTimeout:30 tag:1];
[socket writeData:@"A05" withTimeout:30 tag:1];
[socket readDataWithTimeout:30 buffer:elBuffer bufferOffset:0 maxLength:-1 tag:1];

It works prefectly, except for the fact that the socket server needs a second or so between writes for it to work. I was wondering if anyone has run into the same problem and could shed a light on how to achieve this. Thanks.


Solution

  • I was able to get this to work using the following:

    int i=0;
    for(id aItem in aIDs) {
      NSString *directCommand = [NSString stringWithFormat:@"A%@",aItem];
      [self performSelector:@selector(fSend:) withObject:directCommand afterDelay:(2.0*i)];
      i++;
    }
    [socket readDataWithTimeout:30 buffer:elBuffer bufferOffset:0 maxLength:-1 tag:1];
    
    -(void)fSend : (NSString *)aCommand {
      [socket writeData:aCommand withTimeout:30 tag:1];
    }
    

    This gives me a 2 seconds between performing the writeData without having to freeze the app and without flooding my equipment with writes.