i am receiving string messages over a socket connection and as i am receiving the bytes from the associated filehandle i create a string from them.
[NSString stringWithCString:[data bytes] encoding:NSASCIIStringEncoding]
now this kind of works fine but as i tried to log these strings i get them correctly most of the time but in between i get some garbage characters. i tried it with utf8bytes and with ascii like above (the messages are ascii anyway).
i am receiving data through notifications like this:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveData:) name:NSFileHandleDataAvailableNotification object:fileHandle];
[fileHandle waitForDataInBackgroundAndNotify];
i suppose that once the load of messages increases, the mangled string parts show up in the log. the message itself is clean and strictly alphanumeric (plus the delimiter @”;” and dots in floats)
or do the weird string parts have nothing to do with the messages and i just got it wrong using the socket to read the data?
any help is appreciated!
You are probably munging up your data with the way you are converting it. Data is not guaranteed to be delivered in perfect C style string boundaries. Calling
stringWithCStringis reading each data buffer delivered up to the null character then disposing any bytes remaining. You should accumulate all your data buffers before performing any conversion.