2011-12-15 62 views
1

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

- (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); 
} 

请帮帮忙,如果有另一种方式,我愿意去尝试,因为我越来越绝望......

+0

试着看看XMPP框架。它工作得很好。 https://github.com/robbiehanson/XMPPFramework – 2011-12-15 20:38:22

+0

感谢您的回答,但我不确定XMPP是我需要的。如果是这样,你能否指出我可以在哪里看到它如何与Java套接字服务器协同工作? – iblagajic 2011-12-15 21:26:10

回答

0

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

协议指定了什么?

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

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