我似乎找不到我的套接字为null的位置。我遇到了错误:
错误:CFSocketSetAddress绑定失败:1
我不想固定端口号,因为我有一个客户端每次都连接在不同的端口号上,并且它通过相同的protocolIdentifier查找服务器。
我的代码如下:
listenSocket = CFSocketCreate(kCFAllocatorDefault,
PF_INET,
SOCK_STREAM,
IPPROTO_TCP,
kCFSocketAcceptCallBack,
(CFSocketCallBack)&ServerStubAcceptCallback,
&socketContext);
if (NULL == listenSocket)
//TODO: raise exception etc...
return NO;
int yes = 1;
setsockopt(CFSocketGetNative(listenSocket), SOL_SOCKET, SO_REUSEADDR, (void *)&yes, sizeof(yes));
struct sockaddr_in listenSocketAddress;
memset(&listenSocketAddress, 0, sizeof(listenSocketAddress));
listenSocketAddress.sin_len = sizeof(listenSocketAddress);
listenSocketAddress.sin_family = AF_INET;
listenSocketAddress.sin_port = htons(self.listenPort);
listenSocketAddress.sin_addr.s_addr = htonl(INADDR_ANY);
NSData *listenSocketAddressData = [NSData dataWithBytes:&listenSocketAddress length:sizeof(listenSocketAddress)];
listenSocketAddressData = (NSData *)CFBridgingRelease(CFSocketCopyAddress(listenSocket));
if (kCFSocketSuccess != CFSocketSetAddress(listenSocket,(CFDataRef)listenSocketAddressData))
{
if (listenSocket)
CFRelease(listenSocket);
listenSocket = NULL;
return NO;
}
memcpy(&listenSocketAddress, [listenSocketAddressData bytes], [listenSocketAddressData length]);
self.listenPort = ntohs(listenSocketAddress.sin_port);
// create a RunLoopSource from the socket
CFRunLoopRef runLoop = CFRunLoopGetCurrent();
CFRunLoopSourceRef listenSocketSource = CFSocketCreateRunLoopSource(kCFAllocatorDefault, listenSocket, 0);
// add it to the runloop
CFRunLoopAddSource(runLoop, listenSocketSource, kCFRunLoopCommonModes);
CFRelease(listenSocketSource);