简体   繁体   English

AsyncSocket:始终监听传入的TCP消息

[英]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.

相关问题 Spring Integration TCP Server打印传入消息 - Spring integration TCP server print incoming messages 如何使用 Kestrel ConnectionHandler 处理传入的 TCP 消息? - How to handle incoming TCP messages with a Kestrel ConnectionHandler? Android-在后台监听传入的TCP / Socket消息 - Android - Listening for incoming TCP/Socket messages in background 从TCP服务器侦听传入消息会导致StackOverflow - Listening for incoming messages from TCP server causes StackOverflow VB6异步Tcp客户端截断传入的消息 - VB6 Asynchronous Tcp Client truncates incoming messages 如何将AsyncSocket readDataToLength分析为相应的Wireshark TCP数据包? - How to analyze the AsyncSocket readDataToLength to a corresponding Wireshark TCP packet? AsyncSocket和CFSocket,如何设置TCP的紧急标志? - AsyncSocket and CFSocket, how to set TCP's Urgent Flag? @Scheduled非阻塞ServerSocketChannel accept()会丢失传入的TCP消息吗? - Could a @Scheduled non-blocking ServerSocketChannel accept() miss incoming TCP messages? 有没有办法让 tcp 服务器发送响应而不是回显传入消息? - Is there a way to get tcp server to send responses other than echoing incoming messages? 侦听传入的TCP连接 - listening for incoming TCP connections
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM