3

我发现 GCDAsyncSocket 的 didReadData 回调不直观的一件事是,除非您发出另一个 readData,否则它不会再次被调用。为什么要这样设计?期望库的用户启动另一个读取调用以获得回调是否正确,或者这是一个设计缺陷?

例如

- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket {
     ...
    // initiate the first read
    self.socket = newSocket;
    [self.socket readDataWithTimeout:-1 tag:0];
}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
    // do what you need with the data...

    // read again, or didReadData won't get called!
    [self.socket readDataWithTimeout:-1 tag:0];
}
4

3 回答 3

7

为什么会这样设计?

只要您只使用过readDataWithTimeout:tag:,只要有新数据到达就调用委托方法似乎更直观。

但是readDataWithTimeout:tag:并不是使用 GCDAsyncSocket 读取数据的唯一方法。还有例如readDataToLength:withTimeout:tag:readDataToData:withTimeout:tag:

这两种方法都在传入数据的特定点调用委托,并且您可能希望在处理的不同点调用不同的委托。

例如,如果您正在处理一个流格式,其中有一个 CRLF 分隔的标头,后跟一个可变长度的主体,其长度在标头中提供,那么您可能希望在readDataToData:withTimeout:tag:调用之间交替调用以读取其标头delimiter 你知道,然后readDataToLength:withTimeout:tag:读取你从标题中提取的长度的正文。

于 2013-03-25T22:01:54.330 回答
1

那是对的; 您应该在委托方法中继续读取循环。

于 2013-03-25T20:21:47.767 回答
0

扩展西蒙詹金斯所说的:

    - (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
    {

        // This method is executed on the socketQueue (not the main thread)
        switch (tag) {
            case CHECK_STAUTS:
                [sock readDataToData:[GCDAsyncSocket ZeroData] withTimeout:READ_TIMEOUT tag:CHECK_STAUTS];
                break;

            default:
                break;
        }


    }



    - (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
    {
        // This method is executed on the socketQueue (not the main thread)
     dispatch_async(dispatch_get_main_queue(), ^{
            @autoreleasepool {

                if (tag == CHECK_STAUTS) {
    //TODO: parse the msg to find the length.
    NSString *msg = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

                    [serverSocket readDataToLength:LENGTH_BODY withTimeout:-1 tag:CHECK_STAUTS_BODY]; 

                } else if (tag == CHECK_STAUTS_BODY) {
//TODO: parse the msg to the body content
    NSString *msg = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
                }

            }
        });


        // Echo message back to client
        //[sock writeData:data withTimeout:-1 tag:ECHO_MSG];
    }
于 2013-10-10T11:39:27.157 回答