【问题标题】:iPhone stream programming (CFStream) Hello WorldiPhone 流式编程 (CFStream) Hello World
【发布时间】:2010-04-08 17:11:55
【问题描述】:

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

这是我的代码:

#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

对于客户端.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];
}

有人知道出了什么问题吗?

【问题讨论】:

    标签: iphone objective-c sockets


    【解决方案1】:

    您的初始化格式不正确。您创建了一个名为 client: 的方法,而不是 init,它接受一个名为 init 的单个未标记参数(默认为 id 或 int——我认为是 id,但我现在想不起来)。由于永远不会调用此方法(客户端),因此您的客户端永远不会连接。相反,将该方法替换为以下内容:

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

    现在,当您调用[Client new] 时,您的客户端实际上将被初始化并调用connect。我还稍微重构了它,使其遵循常见的 Objective-C/Cocoa 初始化模式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-04
      相关资源
      最近更新 更多