开发者

CFNetwork packet read callback not being called (iPhone)

Running on the iPhone simulator, I am listening on a port for packets, but my callback never gets called (and the packets are being sent for sure, checked with wireshark). Simplified code follows:

#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开发者_如何学JAVA 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

Somewhere else in the code, MyListener is instantiated and its method ListenOnPort is called, like so:

myListener = [[MyListener alloc] init];
[myListener ListenOnPort:IN_PORT withCallback:&ReadCallback];

No failures occur, but Data is never received. Source of packets is another computer on the same lan, and like I mentioned, they are seen by wireshark (udp with correct ip and port number).

This is the first time I try to use this framework. Any help is appreciated.


Try changing:

addr.sin_port = port;

To:

addr.sin_port = htons(port);

(The simulator runs on Intel so you need to convert to network order)


Try to replace CFRunLoopGetCurrent() with CFRunLoopGetMain()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜