OGeek|极客世界-中国程序员成长平台

标题: iOS:发送缓冲区中的套接字连接错误 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 14:22
标题: iOS:发送缓冲区中的套接字连接错误

我们尝试了太多不同的方法来解决我们的问题,并且还在网上搜索,但我们只找到了发送字符串而不是字节数组的示例。我们需要通过套接字连接发送字节数组。请阅读下面的问题说明。

我们需要将 wi-fi 设备与 iOS 应用程序连接。我们已经成功连接了设备,但是当我们以字节数组格式发送命令时,它返回 NSStreamEventHasSpaceAvailable 作为响应。这是错误的,我们需要 NSStreamEventHasBytesAvailable 事件。

下面是连接代码:

-(void) initNetworkCommunicationNSString*)strHostName {

CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)strHostName, 2000, &readStream, &writeStream);

inputStream = (NSInputStream *)readStream;
outputStream = (NSOutputStream *)writeStream;



[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];

}

当连接打开时,我们调用下面的方法来发送命令:

 - (IBAction) sendCommand {
 unsigned char *buffer[5] = {0x3a,0x04,0x01,0x07,0x0c};

NSData *data = [NSData dataWithBytes:buffer length:5];
[outputStream write:[data bytes] maxLength:5];

}

所以 sendCommand 方法存在一些问题,因为我们正在接收 NSStreamEventHasSpaceAvailable ,这是错误的。因为它应该在响应中返回 NSStreamEventHasBytesAvailable。谁能帮助我们如何在 iOS 中发送字节数组 {0x3a,0x04,0x01,0x07,0x0c},以便我们可以接收 NSStreamEventHasBytesAvailable 事件。

根据命令手册,当设备接收到正确格式的命令时,它将返回确认。以下是手册说明。

All commands are 16 bits and are placed in the Data byte 1(MSB) and Data byte 2(LSB). The response to a command can either be a specific response relating to the command or a simple response. The three simple responses are ACK, NAK and UNK. An ACK signifies that the command was received successfully. A NAK indicates that there was an error with either the length byte or an incorrect checksum was calculated. An UNK response indicates that the recipient does not recognize the command that was sent.

所以我们应该收到上述任何标志(ACK OR NAK OR UNK),但我们收到的是 NSStreamEventHasSpaceAvailable,这是错误的。任何人请帮我解决我的问题。

提前致谢。



Best Answer-推荐答案


NSStreamEventHasSpaceAvailable 是在输出流上发送数据后接收的正确事件 - 它表明您可以写入至少一个字节而不会阻塞(即有空间可写入数据)。 NSstreamEventHasBytesAvailable 将在与输入流关联的套接字上接收到数据时针对输入流发出信号,以指示您可以在不阻塞的情况下发出读取。

如果您发送数据以响应该数据的设备,那么我希望您在 inputStream

上收到 NSStreamEventHasBytesAvailable

关于iOS:发送缓冲区中的套接字连接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28741114/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4