简体   繁体   中英

AsyncSocket: always listen to incoming TCP messages

I would like to have a service which connects via TCP to a server and then continuously listens to incoming data. I'm using CocoaAsyncSocket which I'm using in the following way:

self.socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *err = nil;
if (![self.socket connectToHost:@"..." onPort:... error:&err]) {
    return;
}

[self.socket readDataWithTimeout:-1 tag:1];

and then in the reading delegate method:

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
    NSLog(@"%@", data);
    [self.socket readDataWithTimeout:-1 tag:1];
}

is this correct that I'm immediately calling readDataWithTimout:tag: again? Or is there a (better) way to always listen to incoming messages?

For what you are doing this is fine. You need to call -[readDataWithTimeout] in -didReadData, because otherwise you would only receive the first message from the server. GCDAsyncSocket is designed this way, because there are a few other ways you can receive incoming data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM