我目前正在尝试从我的iPhone向运行正常服务器(通过iPhone上的telnet测试)的远程计算机发送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];
}有人知道哪里出了问题吗?
发布于 2010-04-09 01:44:38
您的初始化格式不正确。您创建了一个名为client:的方法,而不是init,该方法接受一个名为init的未标记参数(缺省值为id或int--我想是id,但我现在记不起来了)。由于此方法(客户端)从不调用,因此您的客户端永远不会连接。相反,请将该方法替换为以下内容:
- (id)init
{
if( (self = [super init]) ) {
[self connect];
}
return self;
}现在,当您调用[Client new]时,您的客户端实际上将被初始化并调用connect本身。我还稍微重组了它,使其遵循通用的Objective-C/Cocoa初始化模式。
https://stackoverflow.com/questions/2601950
复制相似问题