创建socket stream

来源:互联网 发布:java applet程序实例 编辑:程序博客网 时间:2024/05/01 01:09

转自https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Streams/Articles/NetworkStreams.html#

//apple_ref/doc/uid/20002277-BCIDFCDI

    The NSStream class does not support connecting to a remote host on iOS. CFStream does support this behavior, however, and once you have created your streams with the CFStream API, you can take advantage of the toll-free bridge between CFStream and NSStream to cast your CFStreams to NSStreams. Just call theCFStreamCreatePairWithSocketToHost function, providing a host name and a port number, to receive both a CFReadStreamRef and a CFWriteStreamRef for the given host. You can then cast these objects to an NSInputStream and an NSOutputStream and proceed.

    Listing 1 illustrates the use of CFStreamCreatePairWithSocketToHost. This example shows the creation of both a CFReadStreamRef object and aCFWriteStreamRef object. If you want to receive only one of these objects, just specify NULL as the parameter value for the unwanted object.

Listing 1  Setting up a network socket stream


- (IBAction)searchForSite:(id)sender


{


    NSString *urlStr = [sender stringValue];


    if (![urlStr isEqualToString:@""]) {


        NSURL *website = [NSURL URLWithString:urlStr];


        if (!website) {


            NSLog(@"%@ is not a valid URL");


            return;


        }


 


        CFReadStreamRef readStream;


        CFWriteStreamRef writeStream;


        CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)[website host], 80, &readStream, &writeStream);


 


        NSInputStream *inputStream = (__bridge_transfer NSInputStream *)readStream;


        NSOutputStream *outputStream = (__bridge_transfer NSOutputStream *)writeStream;


        [inputStream setDelegate:self];


        [outputStream setDelegate:self];


        [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];


        [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];


        [inputStream open];


        [outputStream open];


 


        /* Store a reference to the input and output streams so that


           they don't go away.... */


        ...


    }



}

Listing 2  Handling stream event
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
 
    switch(eventCode)
   
    {

    case NSStreamEventOpenCompleted: 

{

NSLog(@"Opened connection");

break;

        }

         case NSStreamEventErrorOccurred: 

{

            NSLog(@"Stream open error");

break;

        }

 
        case NSStreamEventHasBytesAvailable://Handling a bytes-available event
      {
            if(!_data) {
                _data = [[NSMutableData data] retain];
            }
            uint8_t buf[1024];
            unsigned int len = 0;
            len = [(NSInputStream *)stream read:buf maxLength:1024];
            if(len) {
                [_data appendBytes:(const void *)buf length:len];
                // bytesRead is an instance variable of type NSNumber.
                [bytesRead setIntValue:[bytesRead intValue]+len];
            } else {
                NSLog(@"no buffer!");
            }
            break;
        }

        case NSStreamEventHasBytesAvailable://Handling a space-available event
        {
            if(!_data) {
                _data = [[NSMutableData data] retain];
            }
            uint8_t buf[1024];
            unsigned int len = 0;
            len = [(NSInputStream *)stream read:buf maxLength:1024];
            if(len) {
                [_data appendBytes:(const void *)buf length:len];
                // bytesRead is an instance variable of type NSNumber.
                [bytesRead setIntValue:[bytesRead intValue]+len];
            } else {
                NSLog(@"no buffer!");
            }
            break;
        }
                   case NSStreamEventEndEncountered://Closing and releasing the NSInputStream object

         {

              [stream close];

              [stream removeFromRunLoop:[NSRunLoop currentRunLoop]

                forMode:NSDefaultRunLoopMode];

              [stream release];

              stream = nil; // stream is ivar, so reinit it

              break;

          }


         // continued ...


    }

}



        

原创粉丝点击