Created
August 17, 2012 00:03
-
-
Save codeswimmer/3374678 to your computer and use it in GitHub Desktop.
TCP Streaming for iOS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <UIKit/UIKit.h> | |
@interface TESTStreamDelegate : NSObject <NSStreamDelegate> | |
@property (strong, nonatomic) NSInputStream *inputStream; | |
@property (strong, nonatomic) NSOutputStream *outputStream; | |
- (void) request; | |
@end | |
@implementation TESTStreamDelegate | |
@synthesize inputStream; | |
@synthesize outputStream; | |
- (void) request | |
{ | |
NSUInteger portNo = 80; | |
CFStringRef hostName = CFSTR("www.yahoo.co.jp"); | |
CFReadStreamRef readStream; | |
CFWriteStreamRef writeStream; | |
CFStreamCreatePairWithSocketToHost(NULL, hostName, portNo, &readStream, &writeStream); | |
assert(CFGetRetainCount(readStream) == 1L); | |
assert(CFGetRetainCount(writeStream) == 1L); | |
self.inputStream = (__bridge_transfer NSInputStream*) readStream; | |
self.outputStream = (__bridge_transfer NSOutputStream*) writeStream; | |
[inputStream setDelegate:self]; | |
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; | |
[outputStream setDelegate:self]; | |
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; | |
[inputStream open]; | |
[outputStream open]; | |
const char *request = "GET / HTTP/1.0\r\nHost: www.yahoo.co.jp\r\n\r\n"; | |
[outputStream write:(const uint8_t*)request maxLength:strlen(request)]; | |
} | |
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode | |
{ | |
switch (eventCode) { | |
case NSStreamEventHasBytesAvailable: { | |
unsigned char buf[1024]; | |
NSUInteger len = [(NSInputStream*)aStream read:buf maxLength:1024]; | |
NSString *str = [[NSString alloc] initWithBytes:buf length:1024 encoding:NSUTF8StringEncoding]; | |
NSLog(@"%@", str); | |
} | |
break; | |
default: | |
break; | |
} | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment