Sth与ios服务器端的CFSocket错误,不会调用回调函数

时间:2014-06-20 16:21:59

标签: ios sockets connection server-configuration cfsocket

我想在iphone上建立一个在线游戏,现在我需要编码以建立两个玩家之间的连接,而不是bonjour,我必须使用一些套接字方式来做到这一点。 这是我在客户端上的代码,它在Mac上运行时有效,但在Iphone设备测试时无效。我真的不知道哪里出错了,这让我很困扰。有人有同样的问题吗? 日志说套接字已经在监听端口,但是AcceptCallback函数不会被调用,出了什么问题?

CFSocketRef sserveripv4;

CFSocketContext CTX4 = { 0, NULL, NULL, NULL, NULL };

sserveripv4 = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP,
                         kCFSocketAcceptCallBack, AcceptCallback, &CTX4);

CFSocketRef sserveripv6;

CFSocketContext CTX6 = { 0, NULL, NULL, NULL, NULL };

sserveripv6 = CFSocketCreate(kCFAllocatorDefault, PF_INET6, SOCK_STREAM, IPPROTO_TCP,
                             kCFSocketAcceptCallBack, AcceptCallback, &CTX6);

if (sserveripv4 == NULL)
    return -1;
if (sserveripv6 == NULL) {
    return -2;
}

int yes = 1;
setsockopt(CFSocketGetNative(sserveripv4), SOL_SOCKET, SO_REUSEADDR,
           (void *)&yes, sizeof(yes));
setsockopt(CFSocketGetNative(sserveripv6), SOL_SOCKET, SO_REUSEADDR,
           (void *)&yes, sizeof(yes));

struct sockaddr_in sin; 
memset(&sin, 0, sizeof(sin));             
sin.sin_len = sizeof(sin);
sin.sin_family = AF_INET;                  
sin.sin_port = htons(PORT);                
sin.sin_addr.s_addr = htonl(INADDR_ANY);       
CFDataRef sincfd = CFDataCreate(kCFAllocatorDefault, (UInt8*)&sin, sizeof(sin));
CFSocketSetAddress(sserveripv4, sincfd);
CFRelease(sincfd);

struct sockaddr_in6 sin6; 
memset(&sin6, 0, sizeof(sin6));             
sin6.sin6_len = sizeof(sin6);
sin6.sin6_family = AF_INET6;                 
sin6.sin6_port = htons(PORT);                
sin6.sin6_addr = in6addr_any;       
CFDataRef sin6cfd = CFDataCreate(kCFAllocatorDefault, (UInt8*)&sin6, sizeof(sin6));
CFSocketSetAddress(sserveripv6, sin6cfd);
CFRelease(sin6cfd);

CFRunLoopSourceRef socketsource = CFSocketCreateRunLoopSource(kCFAllocatorDefault, sserveripv4, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), socketsource, kCFRunLoopDefaultMode);

CFRunLoopSourceRef socketsource6 = CFSocketCreateRunLoopSource(kCFAllocatorDefault, sserveripv6, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), socketsource6, kCFRunLoopDefaultMode);

printf("Socket listening on port %d\n", PORT);

0 个答案:

没有答案