我真的很想使用NSInputStream的getBuffer:length:
方法。 經過大量研究,我找不到使用此方法的有效示例,因爲大多數人確實需要read: maxLength:
。NSInputStream getBuffer:長度:不起作用?
所以現在對周圍的一些事實: *我爲iPhone開發應用程序,iOS版3.1.3 *我已經建立了通過套接字 *該網絡連接實際工作網絡通信;所以我沒有忘記添加一個流到runloop或一個有效的委託或這樣的事情 - 它已經工作 *我只在網絡上發送和接收字符串。 *我設置了一個有效的代表,正確實施stream: handleEvent:
(區分收到的事件並採取適當的措施)。 我不確定接收代碼是否100%正確,因爲我有時會收到兩次消息。 這也可能是由於我與之通信的設備上存在錯誤的實現。 爲了弄清楚哪一點是最後一點,我試圖找出有多少字節真的在接收緩衝區,當我收到「NSStreamEventHasBytesAvailable」事件。 由於我不確定我的實現是否正確,但我想知道實際收到的字節數,所以我想使用getBuffer: length:
並查看後面的長度。 奇怪的是:長度永遠不會打印在控制檯上,因爲 [((NSInputStream *) stream) getBuffer: &buf length: &numBytes]
總是計算爲FALSE。 無論如何,這部分代碼事後工作正常,在緩衝區中接收消息並正確轉發 - 效果很好。 問題依然存在:爲什麼getBuffer: length:
沒有工作? 感興趣的代碼是在這裏:
` 情況下NSStreamEventHasBytesAvailable:{
uint8_t *buf;
unsigned int numBytes;
if ([((NSInputStream *) stream) getBuffer: &buf length: &numBytes]) {
NSLog(@"\t\tBytes in the buffer: %i", &numBytes);
}
uint8_t buffer[BUFFER_SIZE];
int len = [((NSInputStream *) stream) read: buffer
maxLength: BUFFER_SIZE];
NSLog(@"\tread: %i bytes", len);
/*
if len > 0: len is equal to the filled byte elements
if len == 0: end of buffer was reached while reading
if len < 0: something terrible happened...
*/
if (len > 0) {
/* 1. create string from received byte buffer */
NSString *msg = [[NSString alloc] initWithBytes: buffer length: len encoding: NSASCIIStringEncoding];
NSLog(@"\tcontained message: %@", msg);
/* 2. inform communicator about received message */
[communicator received: msg];
[msg release];
}
if (len < 0) {
[communicator received: @"Error!"];
}
break;
}
`
將是很好,如果有人可以幫助我!
嗨,你可以檢查我的[關於在Swift中getBuffer的問題](http://stackoverflow.com/questions/40045665/size-of-the-nsinputstream-buffer)?我有一個很奇怪的問題,高級用戶提出的答案不起作用。問候! – 2016-10-16 01:29:27