我真的需要一些帮助来做我的项目。我需要与用Java编写的服务器交换数据。我试过使用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);
}请帮帮我,如果有其他方法,我愿意尝试,因为我越来越绝望…
发布于 2011-12-20 10:32:31
我看到您正在发送XML,请求数据的末尾没有特定的终止符,但是您希望服务器发送一个以\r\n终止的响应?
协议规定了什么?
通过tcp发送和接收数据是造成混淆的常见原因,因为tcp是基于流的。它没有单独读/写的概念。它将所有数据从概念上视为永无止境的流。该协议规定了消息边界。有关更好的解释,请参阅GCDAsyncSocket的wiki中的“常见陷阱”文章:https://github.com/robbiehanson/CocoaAsyncSocket/wiki/CommonPitfalls
我认为这将有助于解释很多。
https://stackoverflow.com/questions/8525218
复制相似问题