我在使用 GCDAsyncSocket 通过套接字发送消息时遇到问题。我建立连接并尝试向服务器发送消息,但是当应用程序退出时正在发送消息。我需要一种方法来做到这一点。我试过 [asyncSocket 断开连接];但它没有任何改变......请帮忙。这是我的代码的一部分:
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>someusername</username></userProperties></root>";
NSData *requestData = [requestStr dataUsingEncoding:NSUTF8StringEncoding];
[asyncSocket writeData:requestData withTimeout:1.0 tag:0];
NSData *receivedData;
[asyncSocket readDataToData:receivedData withTimeout:2.0 tag:0];
NSString *httpResponse = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(@"%@",httpResponse);