2010-04-08 106 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初始化模式。