[英]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. 我想拥有一个通过TCP连接到服务器,然后连续侦听传入数据的服务。 I'm using CocoaAsyncSocket which I'm using in the following way: 我正在以以下方式使用CocoaAsyncSocket :
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? 我立即立即再次调用readDataWithTimout:tag:
是否正确? 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. 您需要在-didReadData中调用-[readDataWithTimeout],因为否则,您只会收到来自服务器的第一条消息。 GCDAsyncSocket is designed this way, because there are a few other ways you can receive incoming data. GCDAsyncSocket是通过这种方式设计的,因为还有其他几种可以接收传入数据的方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.