我正在使用CocoaAsyncSocket,我需要创建一个向服务器发送消息并等待服务器回复的函数,在委托方法中它确实接收服务器响应但是我需要发送消息的函数等待服务器回复并回复。
- (NSString *)sendMessage:(NSString *)message{
NSError *err = nil;
if (![socket connectToHost:@"192.168.1.20" onPort:52523 error:&err]) // Asynchronous!
{
NSLog(@"Error is : %@", err);
}
[socket readDataWithTimeout:-1 tag:1];
NSData* data =[message dataUsingEncoding:NSUTF8StringEncoding];
[socket writeData:data withTimeout:-1 tag:1];
NSString *xmlString = [[NSString alloc] init];
// Here I need the function wait and receive the response
return xmlString;
}
答案 0 :(得分:1)
如果您需要同步发送内容,为什么不建立请求并使用NSURLConnection api,如下所示:
NSData* data = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
这将阻止,直到您收到回复。
如果您想继续使用异步套接字方法但强行使其成为同步调用,您可以通过添加以下方法来执行此操作:
@property (nonatomic, assign) BOOL com_private_condition;
@property (nonatomic, assign) NSThread* com_private_theWaitingThread;
...
@synthesize com_private_condition;
@synthesize com_private_theWaitingThread;
...
- (BOOL)waitForConditionWithTimeout:(NSTimeInterval)aTimeout
{
self.com_private_condition = NO;
self.com_private_theWaitingThread = [NSThread currentThread];
NSDate* theStartDate = [NSDate date];
NSDate* theEndDate = [NSDate dateWithTimeIntervalSinceNow:aTimeout];
do
{
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
beforeDate:theEndDate];
NSTimeInterval theElapsedTime = -[theStartDate timeIntervalSinceNow];
if (theElapsedTime >= aTimeout)
{
return NO;
}
if (self.com_private_condition)
{
return YES;
}
} while (YES);
}
- (void)signalCondition
{
[self performSelector:@selector(com_private_signalCondition:)
onThread:self.com_private_theWaitingThread
withObject:nil waitUntilDone:NO];
}
- (void)com_private_signalCondition:(id)aParam
{
self.com_private_condition = YES;
}
现在让你的方法像这样
- (NSString *)sendMessage:(NSString *)message{
NSError *err = nil;
if (![socket connectToHost:@"192.168.1.20" onPort:52523 error:&err]) // Asynchronous!
{
NSLog(@"Error is : %@", err);
}
[socket readDataWithTimeout:-1 tag:1];
NSData* data =[message dataUsingEncoding:NSUTF8StringEncoding];
[socket writeData:data withTimeout:-1 tag:1];
//make xmlString a variable on your class and set it in your async socket callback when you get the data. once the wait is over just return it.
//NSString *xmlString = [[NSString alloc] init];
// Here I need the function wait and receive the response
//call read and then wait
[socket readDataWithTimeout:-1 tag:1];
[self waitForConditionWithTimeout:9999.0]; //or some other wait timeout of your choosing
//this will block until [self signalCondition] is called by your socket callbacks.
return self.xmlString;
}
现在在你的CocoaAsyncSocket回调套接字中:didReadData:withTag:和socket:didDisconnectWithError:确保你调用
[self signalCondition];
一旦调用,等待方法将继续,并且您只是使异步调用同步。