Im using input streams to communicate with a POS device.
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
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:
[oStream write:(uint8_t *)[request UTF8String] maxLength:[request length]];
3) when the response arrives i capture it and send it to the parser:
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
That's because your buffer
string is not \\0
(NULL) terminated. Maybe 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
. Even if a response is shorter than it, read:maxLength:
is not guaranteed to read all data at once. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.