gpt4 book ai didi

ios - bytesWritten,但其他设备从未收到 NSStreamEventHasBytesAvailable 事件

转载 作者:可可西里 更新时间:2023-11-01 04:48:20 28 4
gpt4 key购买 nike

我已经在 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:信息响应阿拉斯泰尔的评论:

套接字选项

retain、release 和 copyDescription 回调设置为 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;
}

Runloop 调度

是的,所有 4 个流都在运行循环中安排,都使用与我在上面的第一次更新中发布的代码相同的代码。

Runloop 阻塞:

我没有对同步、多线程、NSLocks 等做任何花哨的事情。如果我设置一个按钮操作来将某些内容打印到控制台,它会自始至终都有效——runloop 似乎在正常运行。


Update4,流端口?

Noa 的调试建议给了我进一步检查流属性的想法:

NSNumber *nTest = [self.streamIn propertyForKey:NSStreamSOCKSProxyPortKey]; // always null!

我曾假设流卡在它们的端口上,但令人惊讶的是,nTest 始终为空。它在我的应用程序中为空,这似乎指出了一个问题——但它在有效的教程应用程序中也是空的。如果流在创建后不需要卡在其端口分配上,那么端口属性的用途是什么?

也许端口属性不能直接访问?但是 nTest 在以下内容中也始终为 null:

    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)

最佳答案

问题出在这一行:

CFStreamCreatePairWithSocket(kCFAllocatorDefault, socketNativeHandle, &readStream, NULL);

如果我只在 iPhone 端接收数据,这就没问题了。但是我正在创建一对 流,而不仅仅是一个输入流,所以在这段代码下面我正在创建一个写入流:

CFStreamCreatePairWithSocket(kCFAllocatorDefault, socketNativeHandle, NULL, &writeStream); 

CFStream Reference 说,“如果你传递 NULL [for readStream],这个函数将不会创建一个可读流。”它并没有说如果你传递 NULL,你将呈现一个以前创建的流不可操作。但这显然是发生了什么。

此设置的一个奇怪问题是,如果我首先打开 streamIn,我会遇到相反的问题:iPhone 会获得 hasByteAvailable 事件,但绝不会获得 hasSpaceAvailable 事件。正如问题中所述,如果我查询流的状态,两者都会返回 NSStreamStatusOpen。所以花了很长时间才弄清楚真正的错误在哪里。

(这个顺序流的创建是我几个月前建立的一个测试项目的一个产物,在这个项目中我测试了仅在一个方向或另一个方向上移动的数据。)

解决方案

两个流应该在一行中成对创建:

CFStreamCreatePairWithSocket(kCFAllocatorDefault, socketNativeHandle, &readStream, &writeStream);

关于ios - bytesWritten,但其他设备从未收到 NSStreamEventHasBytesAvailable 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10378001/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com