[英]Garbage reading from NSInputStream
Im using input streams to communicate with a POS device. 我正在使用输入流与POS设备进行通信。
When i send the first request the response is normal. 当我发送第一个请求时,响应是正常的。 The problem comes when i send the second request because the second response is shorter than first one and that content is still in the stream.
当我发送第二个请求时,问题就来了,因为第二个响应比第一个短,并且内容仍在流中。 So i get the following:
所以我得到以下内容:
First response: 第一反应:
<response>A really big response with much more things inside</response>
Second response; 第二反应;
<response>A not so big response</response>more things inside</response>
I do the following: 我执行以下操作:
1) Open the streams 1)打开流
CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)host, [port intValue], &readStream, &writeStream);
iStream = (NSInputStream *)readStream;
oStream = (NSOutputStream *)writeStream;
[iStream setDelegate:self];
[oStream setDelegate:self];
[iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[iStream open];
[oStream open];
2) then i write my request: 2)然后我写我的要求:
[oStream write:(uint8_t *)[request UTF8String] maxLength:[request length]];
3) when the response arrives i capture it and send it to the parser: 3)当响应到达时,我捕获它并将其发送到解析器:
uint8_t buffer[MAX_BUFFER_SIZE];
[iStream read:buffer maxLength:MAX_BUFFER_SIZE - 1];
NSString *response = [NSString stringWithUTF8String:(char *)buffer];
free(buffer);
NSError *error;
NSDictionary *ret =[SimpleXMLConverter dictionaryForXMLString:response error:&error];
After this, i tried to close the streams and open them again before sending the second request 之后,在发送第二个请求之前,我尝试关闭流并再次打开它们
Thanks and regards 谢谢并恭祝安康
PS: its not a blocking issue because i can get the correct substring, but i dont understand why its happening PS:这不是一个阻碍性的问题,因为我可以获得正确的子字符串,但是我不明白为什么会这样
That's because your buffer
string is not \\0
(NULL) terminated. 这是因为您的
buffer
字符串不是\\0
(NULL)终止的。 Maybe uint8_t buffer[MAX_BUFFER_SIZE] = {0};
也许
uint8_t buffer[MAX_BUFFER_SIZE] = {0};
will solve your current problem. 将解决您当前的问题。
However, you should consider one response could be longer than MAX_BUFFER_SIZE - 1
. 但是,您应该考虑一个响应可能比
MAX_BUFFER_SIZE - 1
。 Even if a response is shorter than it, read:maxLength:
is not guaranteed to read all data at once. 即使响应比响应短,也不能保证
read:maxLength:
一次读取所有数据。 You must check the returned value and received data has entire response. 您必须检查返回的值,并且收到的数据具有完整的响应。
Moreover, DO NOT free(buffer)
, because free()
is only for malloc()
ed memory, not for auto variables. 而且,不要
free(buffer)
,因为free()
仅用于malloc()
内存,不适用于自动变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.