我正在写一个可可应用程序。应用程序中有一个套接字,每当套接字变为可读时,我都希望从套接字中读取数据,处理数据,并相应地更新用户界面。我想在主循环中集成读事件检查,也就是说,我想将套接字附加到主循环,并让主循环在套接字变为可读时调用回调。
我写了一个测试应用程序,但由于某种原因,它不起作用:
#include <stdio.h>
#include <Foundation/NSAutoReleasePool.h>
#include <Foundation/NSRunLoop.h>
#include <Foundation/NSPort.h>
@interface MyDelegate : NSObject <NSPortDelegate> {
}
- (void)handlePortMessage:(NSPortMessage *)portMessage;
@end
@implementation MyDelegate
- (void)handlePortMessage:(NSPortMessage *)portMessage {
printf("Haiz\n");
}
@end
int
main() {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSSocketPort *server = [NSSocketPort alloc];
MyDelegate *foo = [MyDelegate alloc];
[server initWithTCPPort: 1234];
[server setDelegate: foo];
[[NSRunLoop mainRunLoop] addPort: server forMode: NSDefaultRunLoopMode];
[[NSRunLoop mainRunLoop] run];
[pool release];
return 0;
}
应用程序应该在本地主机端口1234上监听,每当有人连接到服务器或向服务器发送数据时,应用程序应该在控制台上打印“haiz”。但是这个应用程序什么也不做。这个套接字是创建的,我可以通过telnet连接到端口1234,但是这个应用程序不会向控制台打印任何内容。
我做错什么了?