2010-04-08 105 views
3

我目前正在尝试从我的iPhone发送Hello World到运行工作服务器的远程计算机(通过iPhone上的telnet进行测试)。iPhone流编程(CFStream)Hello World

这里是我的代码:

#import "client.h" 

@implementation client 

- (client*) client:init { 
self = [super init]; 
[self connect]; 
return self; 
} 

- (void)connect { 
     CFWriteStreamRef writeStream; 
     CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)[NSString stringWithFormat: @"192.168.1.1"], 50007, NULL, &writeStream); 
    NSLog(@"Creating and opening NSOutputStream..."); 
    oStream = (NSOutputStream *)writeStream; 
    [oStream setDelegate:self]; 
    [oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; 
    [oStream open]; 
} 

- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode { 
    NSLog(@"stream:handleEvent: is invoked..."); 

    switch(eventCode) { 
     case NSStreamEventHasSpaceAvailable: 
     { 
      if (stream == oStream) { 
       NSString * str = [NSString stringWithFormat: @"Hello World"]; 
       const uint8_t * rawstring = 
    (const uint8_t *)[str UTF8String]; 
       [oStream write:rawstring maxLength:strlen(rawstring)]; 
       [oStream close]; 
      } 
      break; 
     } 
    } 
} 

@end 

对于client.h:

#import <UIKit/UIKit.h> 


@interface client : NSObject { 
NSOutputStream *oStream; 
} 

-(void)connect; 

@end 

最后,在AppDelegate.m:

- (void)applicationDidFinishLaunching:(UIApplication *)application {  

    // Override point for customization after app launch  
    [window addSubview:viewController.view]; 
[window makeKeyAndVisible]; 
[client new]; 
} 

是否有人有任何想法发生了什么问题?

回答

1

你的init格式不正确。您创建了一个名为client:的方法,它取名为init的单个未标记参数(默认为id或int - 我认为id,但我现在不记得)。由于此方法(客户端)从未被调用,您的客户端永远不会连接。相反,用下面的替换方法:

- (id)init 
{ 
    if((self = [super init])) { 
    [self connect]; 
    } 
    return self; 
} 

现在,当你调用[Client new],你的客户实际上将被初始化并自称为connect。我也稍微重构了它,以便它遵循常见的Objective-C/Cocoa初始化模式。