在iPhone模拟器上运行,我正在侦听数据包的端口,但是我的回调永远不会被调用(并且数据包正在被发送,并通过wireshark检查)。简化代码如下:
#define IN_PORT (51112)
static void ReadCallback (CFSocketRef theSocket, CFSocketCallBackType theType, CFDataRef theAddress, const void *data, void *info)
{
NSLog(@"Data received");
}
@implementation MyListener
- (void) ListenOnPort:(uint16_t)port withCallback:(CFSocketCallBack)callback
{
CFSocketContext context = {0,self,NULL,NULL,NULL};
CFSocketRef cfSocket = CFSocketCreate(NULL, PF_INET, SOCK_DGRAM, PPROTO_UDP, kCFSocketReadCallBack, callback, &context);
if (cfSocket==NULL)
NSLog(@"CFSocketCreate failed");
struct sockaddr_in addr;
memset(&addr,0,sizeof(addr));
addr.sin_len = sizeof(addr);
addr.sin_family = AF_INET;
addr.sin_port = port;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
NSData *address = [NSData dataWithBytes:&addr length:sizeof(addr)];
if(kCFSocketSuccess != CFSocketSetAddress(cfSocket, (CFDataRef)address))
NSLog(@"CFSocketSetAddress failed");
CFRunLoopSourceRef rls = CFSocketCreateRunLoopSource(kCFAllocatorDefault, cfSocket, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, kCFRunLoopCommonModes);
CFRelease(rls);
}
@end
代码中的其他地方,MyListener被实例化并调用其方法ListenOnPort,如下所示:
myListener = [[MyListener alloc] init];
[myListener ListenOnPort:IN_PORT withCallback:&ReadCallback];
不会发生故障,但从未收到数据。数据包的来源是同一局域网上的另一台计算机,就像我提到的那样,它们可以被wireshark看到(udp有正确的IP和端口号)。
这是我第一次尝试使用此框架。任何帮助表示赞赏。
答案 0 :(得分:2)
尝试更改:
addr.sin_port = port;
要:
addr.sin_port = htons(port);
(模拟器在英特尔上运行,因此您需要转换为网络顺序)
答案 1 :(得分:2)
尝试用CFRunLoopGetMain()替换CFRunLoopGetCurrent()