首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从CocoaAsyncSocket读取数据

从CocoaAsyncSocket读取数据
EN

Stack Overflow用户
提问于 2012-11-10 23:12:27
回答 1查看 1.1K关注 0票数 1

我使用的是CocoaAsyncSocket,我需要创建一个函数,它向服务器发送一条消息,并等待服务器回复,在委托方法中,它确实接收服务器响应,但我需要发送消息的函数等待服务器回复和返回响应。

代码语言:javascript
复制
- (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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-11-11 02:16:35

如果您需要同步发送某些内容,为什么不构建一个请求并使用NSURLConnection接口,如下所示:

代码语言:javascript
复制
NSData* data = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];   

这将阻止,直到您得到响应。

如果您想继续使用异步套接字方法,但强制将其设置为同步调用,可以通过添加以下方法来实现:

代码语言:javascript
复制
@property (nonatomic, assign) BOOL com_private_condition;
@property (nonatomic, assign) NSThread* com_private_theWaitingThread;

..。

代码语言:javascript
复制
@synthesize com_private_condition;
@synthesize com_private_theWaitingThread;

..。

代码语言:javascript
复制
    - (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;    
}

现在让你的方法像这样

代码语言:javascript
复制
- (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:和套接字:didDisconnectWithError:确保调用

代码语言:javascript
复制
[self signalCondition];

一旦你调用了这个函数,等待方法就会继续,你就完成了一个同步的异步调用。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13323231

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档