我目前正在尝试从我的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
对于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];
}
有人知道出了什么问题吗?
答案 0 :(得分:1)
您的初始化格式不正确。而不是init,你创建了一个名为client:
的方法,它接受一个名为init
的单个未标记参数(默认为id或int - 我认为id,但我记不起来了) 。由于此方法(客户端)从未被调用,因此您的客户端永远不会连接。相反,请使用以下内容替换该方法:
- (id)init
{
if( (self = [super init]) ) {
[self connect];
}
return self;
}
现在,当您致电[Client new]
时,您的客户端实际上会被初始化并自行调用connect
。我还稍微重组了它,以便它遵循常见的Objective-C / Cocoa初始化模式。