Skip to content

Instantly share code, notes, and snippets.

@amachang
Created March 7, 2012 02:28
Show Gist options
  • Save amachang/1990500 to your computer and use it in GitHub Desktop.
Save amachang/1990500 to your computer and use it in GitHub Desktop.
TCP Streaming for iOS
#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