我已经在 iPhone 和 Mac 之间建立了 Bonjour 网络。
用户在 Mac 中呈现的一个表格中选择 iPhone 的网络服务,并在两侧创建并打开一对流。
iPhone 首先向 Mac 发送一个代码(一个整数)。Mac 成功接收到它。
在暂停用户输入和处理后,Mac 开始向 iPhone 发送代码:
NSInteger bytesWritten = [self.streamOut write:buffer maxLength:sizeof(uint8_t)];
// bytesWritten is 1.
但是 iPhone 永远不会收到 NSStreamEventHasBytesAvailable 事件。在此之前我仔细检查过,iPhone 的 NSInputStream 上的 streamStatus 是 2,应该是 NSStreamStatusOpen。
有什么想法可能是错的吗?
更新:我进行了一个测试,其中 Mac 是第一个向 iPhone 发送整数的。同样,我从 Mac 的输出流中得到了 1 的 bytesWritten,但 iPhone 从未得到 NSStreamEventHasBytesAvailable 事件。
所以iPhone的输入流一定有问题。但我仔细检查了:
- iPhone 的 self.streamIn 在 h 文件中正确键入为 NSInputStream
- iPhone 收到 2 个 NSStreamEventOpenCompleted 事件,我检查了流 arg 的类。一个是KindOfClass:[NSOutputStream 类],另一个不是。
- iPhone 永远不会收到 NSStreamEventEndEncountered、NSStreamEventErrorOccurred 或 NSStreamEventNone。
- 如上所述,在 Mac 写入输出流之后,iPhone 的输入流状态为 2,NSStreamStatusOpen。
这是用于创建 iPhone 输入流的代码。它使用 CF 类型,因为它是在 C 风格的套接字回调函数中完成的:
CFReadStreamRef readStream = NULL;
CFStreamCreatePairWithSocket(kCFAllocatorDefault, socketNativeHandle, &readStream, NULL);
if (readStream) {
CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
server.streamIn = (NSInputStream *)readStream;
server.streamIn.delegate = server;
[server.streamIn scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
if ([server.streamIn streamStatus] == NSStreamStatusNotOpen)
[server.streamIn open];
CFRelease(readStream);
}
更新2:响应阿拉斯泰尔评论的信息:
套接字选项
保留、释放和复制描述回调设置为 NULL。optionFlags 设置为acceptCallback。
套接字创建
这是用于在 iPhone 和 Mac 上设置套接字的方法,并附有我评论过的试图弄清楚此代码中实际发生的情况,该方法改编自各种教程和实验(有效):
/**
Socket creation, port assignment, socket scheduled in run loop.
The socket represents the port on this app's end of the connection.
*/
- (BOOL) makeSocket {
// Make a socket context, with which to configure the socket.
// It's a struct, but doesn't require "struct" prefix -- because typedef'd?
CFSocketContext socketCtxt = {0, self, NULL, NULL, NULL}; // 2nd arg is pointer for callback function
// Make socket.
// Sock stream goes with TCP protocol, the safe method used for most data transmissions.
// kCFSocketAcceptCallBack accepts connections automatically and presents them to the callback function supplied in this class ("acceptSocketCallback").
// CFSocketCallBack, the callback function itself.
// And note that the socket context is passed in at the end.
self.socket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP, kCFSocketAcceptCallBack, (CFSocketCallBack)&acceptSocketCallback, &socketCtxt);
// Do socket-creation error checking.
if (self.socket == NULL) {
// alert omitted
return NO;
}
// Prepare an int to pass to setsockopt function, telling it whether to use the option specified in arg 3.
int iSocketOption = 1; // 1 means, yes, use the option
// Set socket options.
// arg 1 is an int. C-style method returns native socket.
// arg 2, int for "level." SOL_SOCKET is standard.
// arg 3, int for "option name," which is "uninterpreted." SO_REUSEADDR enables local address reuse. This allows a new connection even when a port is in wait state.
// arg 4, void (wildcard type) pointer to iSocketOption, which has been set to 1, meaning, yes, use the SO_REUSEADDR option specified in arg 3.
// args 5, the size of iSocketOption, which can now be recycled as a buffer to report "the size of the value returned," whatever that is.
setsockopt(CFSocketGetNative(socket), SOL_SOCKET, SO_REUSEADDR, (void *)&iSocketOption, sizeof(iSocketOption));
// Set up a struct to take the port assignment.
// The identifier "addr4" is an allusion to IP version 4, the older protocol with fewer addresses, which is fine for a LAN.
struct sockaddr_in addr4;
memset(&addr4, 0, sizeof(addr4));
addr4.sin_len = sizeof(addr4);
addr4.sin_family = AF_INET;
addr4.sin_port = 0; // this is where the socket will assign the port number
addr4.sin_addr.s_addr = htonl(INADDR_ANY);
// Convert to NSData so struct can be sent to CFSocketSetAddress.
NSData *address4 = [NSData dataWithBytes:&addr4 length:sizeof(addr4)];
// Set the port number.
// Struct still needs more processing. CFDataRef is a pointer to CFData, which is toll-free-bridged to NSData.
if (CFSocketSetAddress(socket, (CFDataRef)address4) != kCFSocketSuccess) {
// If unsuccessful, advise user of error (omitted)…
// ... and discard the useless socket.
if (self.socket)
CFRelease(socket);
self.socket = NULL;
return NO;
}
// The socket now has the port address. Extract it.
NSData *addr = [(NSData *)CFSocketCopyAddress(socket) autorelease];
// Assign the extracted port address to the original struct.
memcpy(&addr4, [addr bytes], [addr length]);
// Use "network to host short" to convert port number to host computer's endian order, in case network's is reversed.
self.port = ntohs(addr4.sin_port);
printf("\nUpon makeSocket, the port is %d.", self.port);// !!!:testing - always prints a 5-digit number
// Get reference to main run loop.
CFRunLoopRef cfrl = CFRunLoopGetCurrent();
// Schedule socket with run loop, by roundabout means.
CFRunLoopSourceRef source4 = CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0);
CFRunLoopAddSource(cfrl, source4, kCFRunLoopCommonModes);
CFRelease(source4);
// Socket made
return YES;
}
运行循环调度
是的,所有 4 个流都安排在 runloop 中,都使用与我在上面第一次更新中发布的代码相同的代码。
运行循环阻塞:
我没有对同步、多线程、NSLock 等做任何花哨的事情。而且,如果我设置一个按钮操作以将某些内容打印到控制台,它会在整个过程中运行——runloop 似乎运行正常。
Update4,流端口?
Noa 的调试建议给了我进一步检查流属性的想法:
NSNumber *nTest = [self.streamIn propertyForKey:NSStreamSOCKSProxyPortKey]; // always null!
我曾假设流挂在它们的端口上,但令人惊讶的是,nTest
它总是为空。它在我的应用程序中为空,这似乎表明存在问题 - 但在有效的教程应用程序中它也是空的。如果一个流一旦创建就不需要挂起它的端口分配,那么端口属性的目的是什么?
也许端口属性不能直接访问?但nTest
在以下情况下也始终为空:
NSDictionary *dTest = [theInStream propertyForKey:NSStreamSOCKSProxyConfigurationKey];
NSNumber *nTest = [dTest valueForKey:NSStreamSOCKSProxyPortKey];
NSLog(@"\tInstream port is %@.", nTest); // (null)
nTest = [dTest valueForKey:NSStreamSOCKSProxyPortKey];
NSLog(@"\tOutstream port is %@.", nTest); // (null)