gpt4 book ai didi

iphone - 如何通过 NSOutputStream 发送整数?

转载 作者:搜寻专家 更新时间:2023-10-30 20:26:52 26 4
gpt4 key购买 nike

所以我正在制作一个 iOS 应用程序,它不断地通过 NSStream 发送点数组,但是因为有时发送者在接收者接收一个之前写入两个数组,所以我决定先写长度,然后是数组数据本身,以便接收方知道要处理多少字节。

发件人:

if (_outStream && [_outStream hasSpaceAvailable]){
const uint8_t *buffer = [data bytes];
uint64_t length = CFSwapInt64HostToLittle([data length]);
NSLog(@"Sending bytes with length: %llu", length);
int er1 = [_outStream write:(const uint8_t *)&length maxLength:sizeof(length)];
int er2 = [_outStream write:buffer maxLength:length];
if (er1 < 0 || er2 < 0) {
[self _showAlert:@"Failed sending data to peer"];
}
}

接收者:

case NSStreamEventHasBytesAvailable:
{
if (stream == _inStream) {
uint8_t *b;
int len = 0;
len = [_inStream read:b maxLength:8];
uint64_t dataLength = CFSwapInt64LittleToHost(*b);
NSLog(@"Received bytes with length: %llu", dataLength);
if(len < 0) {
if ([stream streamStatus] != NSStreamStatusAtEnd)
[self _showAlert:@"Failed reading data from peer"];
} else if (len > 0){
uint8_t bytes[dataLength];
int length = [_inStream read:bytes maxLength:dataLength];

[currentDownload appendBytes:bytes length:length];
id pointsArray = [NSKeyedUnarchiver unarchiveObjectWithData:currentDownload];
[currentDownload release];
currentDownload = [[NSMutableData alloc] init];
if ([pointsArray isKindOfClass:[NSArray class]]) {
[drawScene addNewPoint:[[pointsArray objectAtIndex:0] CGPointValue] previousPoint:[[pointsArray objectAtIndex:1] CGPointValue]];
}

}
}
break;
}

问题是接收方收到了一个不正确的整数,因此它读取了不正确的字节数。

谁能帮我解决这个问题?

最佳答案

会不会是当您读取数据时,您是从旨在传达长度的介绍性位开始,而不是从实际数据开始?

对于:

[currentDownload appendBytes:bytes length:length];

试着用这样的东西代替:

NSRange rangeLeftover = NSMakeRange(sizeof(uint8_t), [currentDownload length] - sizeof(uint8_t));
NSData *dataLeftover = [currentDownload subdataWithRange:rangeLeftover];
uint8_t bytesLeftover[[dataLeftover length]];
[dataLeftover getBytes:&bytesLeftover length:[dataLeftover length]];
currentDownload = [NSMutableData data]; // clear
[currentDownload appendBytes:bytesLeftover length:[dataLeftover length]];

关于iphone - 如何通过 NSOutputStream 发送整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6479290/

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