A
A
Anton Rudak2015-04-01 15:37:44
Objective-C
Anton Rudak, 2015-04-01 15:37:44

How to change encoding when working with socket?

I'm trying to write my first client application.
piece of code

UInt8 buf[] = "{\"CMD\":\"GETCITY\"}\r\n";
        NSUInteger bytesWritten = CFWriteStreamWrite(writeStream, buf, strlen((char*)buf));
        NSLog(@"Written: %lu", (unsigned long)bytesWritten);
        NSLog(@"buffer: %s", buf);    }
    CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
    if(!CFReadStreamOpen(readStream))
    {
        NSLog(@"Error reading");
    }
    else
    {
        UInt8 bufr[1024];
        NSUInteger bytesRead  = CFReadStreamRead(readStream, bufr, sizeof(bufr));
        NSLog(@"Read: %lu", (unsigned long)bytesRead);
        NSLog(@"buffer: %s", bufr);
        NSString *info =[[NSString alloc] initWithBytes:bufr length:sizeof(bufr) encoding: NSUTF8StringEncoding] ;
       NSLog(@"Ответ сервера: %@", info);

After receiving the response in the bufr variable, I see
"Name":"–¢–µ—Å—Ç–æ–≤–∞—è"

But as soon as I try to convert to UTF8 I get NULL .
Tell me what am I doing wrong? And I suspect that when sending the Cyrillic alphabet to the server, I will also catch the problem.

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
D
Denis, 2015-04-01
@arudak

First you need to come as a "common denominator" - use UTF8.
If a win1251 string comes from the server, then you need to specify this encoding accordingly.
PS
To create a string based on utf8 bytes, you can use
PPS. I would also recommend using something higher for the first network application - NSURLRequest, NSURLConnection from Foundation!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question