// // NSStreamAdditions.h // // Created by John R Chang on Mon Dec 08 2003. // This code is Creative Commons Public Domain. You may use it for any purpose whatsoever. // http://creativecommons.org/licenses/publicdomain/ // #import #import "NSStreamAdditions.h" const int kServerPort = 12345; @interface MyObject : NSObject - (void) didAcceptConnectionWithInputStream:(NSInputStream *)inputStream outputStream:(NSOutputStream *)outputStream; - (void) connectToHostName:(NSString *)hostname port:(unsigned short)port; @end @implementation MyObject - (void) didAcceptConnectionWithInputStream:(NSInputStream *)inputStream outputStream:(NSOutputStream *)outputStream { NSLog(@"Connected!"); [inputStream open]; [outputStream open]; while (1) { NSString * string = [inputStream readString]; if (string == nil) break; // Echo to stdout printf([string UTF8String]); // Echo to outStream BOOL succeed = [outputStream writeString:string]; if (succeed == NO) break; } [inputStream close]; [outputStream close]; NSLog(@"Done."); } - (void) connectToHostName:(NSString *)hostname port:(unsigned short)port { NSInputStream * inputStream; NSOutputStream * outputStream; NSHost * host = [NSHost hostWithName:hostname]; [NSStream getStreamsToHost:host port:kServerPort inputStream:&inputStream outputStream:&outputStream]; [inputStream setDelegate:self]; //[outputStream setDelegate:self]; NSLog(@"Connected!"); [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [inputStream open]; [outputStream open]; } @end int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; MyObject * obj = [MyObject new]; if (argc == 1) { NSLog(@"Listening..."); [NSStream listenOnTCPPort:kServerPort selector:@selector(didAcceptConnectionWithInputStream:outputStream:) target:obj]; } else { NSLog(@"Calling..."); [obj connectToHostName:@"localhost" port:kServerPort]; } [[NSRunLoop currentRunLoop] run]; [obj release]; [pool release]; return 0; }