转自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.... */ |
... |
} |
} |
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode { | ||||||||||||||||||||||||||||||||||
| ||||||||||||||||||||||||||||||||||
switch(eventCode) { | ||||||||||||||||||||||||||||||||||
case NSStreamEventHasBytesAvailable://Handling a bytes-available event
{ [stream close]; [stream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [stream release]; stream = nil; // stream is ivar, so reinit it break; } // continued ... } } | ||||||||||||||||||||||||||||||||||
|