1

I am currently working on a client on iOS for a TCP server. The TCP server works totally fine, I can connect to it with any other client (for example Telnet) and read and receive messages. When one connects for example, it is supposed to send "dh:1000:1" (the numbers might change). If you try it out on Telnet etc. it works. However, I am having difficulties to read that string in XCode. I read from the TCP server the following way:

// -(void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent { 
// etc.....
if (theStream == inputStream) {
            uint8_t buffer[1024];
            int length;

            while ([inputStream hasBytesAvailable]) {
                length = [inputStream read:buffer maxLength:sizeof(buffer)];
                if (length > 0) {

                    NSMutableData* data=[[NSMutableData alloc] initWithLength:0];
                    [data appendBytes: (const void *)buffer length:length];

                    NSString *output = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
                    if (nil != output) {
                        [self messageReceived:output];
                    }

                }
            }
        }

When I use the debugger, the NSString $output$ is ALWAYS an empty string. Interestingly enough though, the $buffer$ does contain the data. If I use the Xcode debugger, I can see the following: enter image description here

You can clearly see that the "dh:1:0..." is there, so the problem is somewhere in this line:

NSString *output = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

But I cannot figure it out :/

Larme
  • 24,190
  • 6
  • 51
  • 81
MrR
  • 171
  • 5
  • Did you try different encoding? Anyway, starting with a "\0" may cause the error. – Larme Jul 01 '14 at 17:26
  • Well, I cannot really do anything about that, that's what I receive from the TcpServer. I have tried to remove all \0 but I don't know how to do that. :/ Yes, I have tried different encodings, like UTF8, Unicode etc. Same result all the time. – MrR Jul 01 '14 at 17:28
  • Maybe try: http://stackoverflow.com/questions/2467844/convert-utf-8-encoded-nsdata-to-nsstring – Larme Jul 01 '14 at 17:32
  • No, it's still empty :/ I am sure it happens because the data contains a lot of "\0s", which in Objective-C is interpreted as the end of the string, but I have no idea how to get rid of them. Can I remove them from the NSData somehow? – MrR Jul 02 '14 at 18:05

0 Answers0