2011-12-15 49 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

我認爲這將有助於解釋很多。