如果您需要同步发送某些内容,为什么不构建请求并使用 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 回调 socket:didReadData:withTag: 和 socket:didDisconnectWithError: 中确保你调用
[self signalCondition];
一旦你调用等待方法将继续,你只是使异步调用同步。