1

我想在 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);
4

0 回答 0