1

私は 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;
}
4

1 に答える 1

2

同期的に何かを送信する必要がある場合は、リクエストを作成して、次のように 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];

待機中のメソッドを呼び出すと、非同期呼び出しが同期されます。

于 2012-11-10T18:16:34.633 に答える