我正在使用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;
}

最佳答案

如果您需要同步发送内容,为什么不构建请求并使用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];

调用后,等待方法将继续,您只需进行异步调用即可。

10-08 12:11