开发者

iPhone stream programming (CFStream) Hello World

I am currently trying to send a Hello World from my iPhone to a remote computer running a working server (tested by telnet on iPhone).

Here is my code :

#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];
  [oSt开发者_如何学编程ream 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

For the client.h :

#import <UIKit/UIKit.h>


@interface client : NSObject {
 NSOutputStream *oStream;
}

-(void)connect;

@end

Finally, in the AppDelegate.m :

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

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

Does someone has any idea of what is going wrong?


Your init format is incorrect. Instead of init, you created a method called client: which takes a single, unlabeled parameter (which defaults to either id or int--I think id but I can't recall at the moment) named init. Since this method (client) is never called, your client never connects. Instead, replace that method with the following:

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

Now, when you call [Client new], your client will actually be initialized and call connect on itself. I also slightly restructured it so that it follows the common Objective-C/Cocoa initialization pattern.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜