0

在我的应用程序中,我需要在通过网络执行某些操作时使用轮询而不是运行循环。

我的代码如下所示

-(id) init
{
    self = [super init];
    if (self) {
    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    NSURL *host = [NSURL URLWithString:@"http://localhost/"];
    CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)([host host]), 5525, &readStream, &writeStream);
    _writeStream = [[NSOutputStream alloc] initToMemory];
    _readStream = (__bridge NSInputStream *)(readStream);
    _writeStream = (__bridge NSOutputStream *)(writeStream);
    [_readStream open];
    [_writeStream open];
  }
   return self;
}

-(void) writeIntoNetworkWith:(NSString *)info
{
if ([self.writeStream hasSpaceAvailable]) {
    NSData * data = [[NSData alloc] initWithData:[info dataUsingEncoding:NSUTF8StringEncoding]];
    [self.writeStream write:[data bytes] maxLength:[data length]];
}
else
    NSLog(@"Write Stream Not Available");
}
-(NSString *) readFromNetwork
{
   NSMutableString * send;
   if ([self.readStream hasBytesAvailable])
  {
    uint8_t buffer[1024];
    int len;
    len = [self.readStream read:buffer maxLength:1024];
    if (len >0)
    {
        send = [[NSMutableString alloc] initWithBytes:buffer length:len encoding:NSUTF8StringEncoding];
    }
}
return send;
}

viewControler.m 如下

- (void)viewDidLoad {
  [super viewDidLoad];
  SuperTestClass * n = [[SuperTestClass alloc]init];
  NetworkReadAndWrite * obj = [[NetworkReadAndWrite alloc]init];
  [obj writeIntoNetworkWith:@"Hello World"];
  [obj readFromNetwork];
}

服务器收到一些数据后回复“Hello”消息

在运行上面的代码时,它总是返回有 noSpaceAvailable/ noBytesAvailable 可以分别从输出和输入流中写入或读取。

我想知道我是否在这里遗漏了什么。

4

1 回答 1

1

弄清楚了。是一个愚蠢的错误。应该等到 readstream 有可供读取的字节。

while(1)
{

    if ([self.readStream hasBytesAvailable])
    {
        uint8_t buffer[1024];
        int len;
        len = [self.readStream read:buffer maxLength:1024];
        if (len >0)
于 2015-07-10T20:33:19.800 回答