首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >iPad GCDAsyncSocket无法读取

iPad GCDAsyncSocket无法读取
EN

Stack Overflow用户
提问于 2011-12-16 03:01:46
回答 1查看 2.4K关注 0票数 1

我真的需要一些帮助来做我的项目。我需要与用Java编写的服务器交换数据。我试过使用GCDAsyncSocket,我可以向服务器发送消息,在服务器上读取它,但是当服务器向客户端发送响应时,我不能(不知道如何)在客户端读取它。下面是我的代码的一部分:

代码语言:javascript
复制
- (void) someMethod{
    NSError *err = nil;
    asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    if(![asyncSocket connectToHost:@"localhost" onPort:7777 error:&err]){
        // If there was an error, it's likely something like "already connected" or "no delegate set"
        NSLog(@"I goofed: %@", err);
    }
    NSString *requestStr = @"<?xml version='1.0' encoding='UTF-8' standalone='yes' ?><root><service>1</service><type>1</type><userProperties><username>ivo</username></userProperties></root>";
    NSData *requestData = [requestStr dataUsingEncoding:NSUTF8StringEncoding];

    [asyncSocket writeData:requestData withTimeout:-1.0 tag:0];

    [asyncSocket readDataToData:[GCDAsyncSocket CRLFData] withTimeout:1.0 tag:0];
    [asyncSocket disconnectAfterWriting];
}

- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag{
    if (tag == 0)
        NSLog(@"First request sent");
    else if (tag == 2)
        NSLog(@"Second request sent");
}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@",str);
}

请帮帮我,如果有其他方法,我愿意尝试,因为我越来越绝望…

EN

回答 1

Stack Overflow用户

发布于 2011-12-20 10:32:31

我看到您正在发送XML,请求数据的末尾没有特定的终止符,但是您希望服务器发送一个以\r\n终止的响应?

协议规定了什么?

通过tcp发送和接收数据是造成混淆的常见原因,因为tcp是基于流的。它没有单独读/写的概念。它将所有数据从概念上视为永无止境的流。该协议规定了消息边界。有关更好的解释,请参阅GCDAsyncSocket的wiki中的“常见陷阱”文章:https://github.com/robbiehanson/CocoaAsyncSocket/wiki/CommonPitfalls

我认为这将有助于解释很多。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8525218

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档