IOS programming-Socket transmission of Chinese Characters
In Socket programming, the client uses
CFReadStreamRef readStream;CFWriteStreamRef writeStream;
Obtain the input and output streams.
After the proxy is set, use
uint8_t buffer[1024];length = (int)[self.inputStream read:buffer maxLength:sizeof(buffer)];
Transmits the content in inputStream to the buffer, where buffer is an array of the uint8_t type. Uint8_t indicates an unsigned 8-digit integer. To read uint8_t data to a string, we first read it to NSData type data and convert it to NSString.
NSMutableData *inputData = [[NSMutableData alloc]init];[inputData appendBytes:buffer length:length];
Finally, convert NSData to NSString.
NSString *resultString = [[NSString alloc]initWithData:inputData encoding:NSUTF8StringEncoding];
So far, we have successfully read the content of the Socket input stream. However, when the input content contains Chinese characters, we find that NSData is printed with data, not empty, but NSString is empty.
After inspection, we found that there was a problem during data transmission on the server.
Original method:
// Use NSString to customize the message content uint8_t buffer [1024]; NSString * toSend = @ "Welcome to access port 5076"; memcpy (buffer, [toSend UTF8String], [toSend length] + 1); CFWriteStreamWrite (stream, buffer, 1 + strlen (const char *) buffer ));
In this case, the [NSString length] in OC records the length of Chinese characters as 1 when calculating the string length. however, in the use of memcpy function, Chinese characters will be converted to the UTF-8 format, occupies 4 bits, so each transmission of a Chinese character, in fact, the lack of 3 bits. In this way, the NSData received by the client is actually incomplete NSData, And the OC cannot be converted to NSString normally.
Solution 1: Assume that n Chinese characters are transmitted, change the last parameter of the memcpy function to [toSend length] + 1 + 3 * n;
Obviously, this scheme is not desirable, because most of the time we do not know the length of the Chinese characters to be transmitted.
Solution 2: Since the buffer length to be transmitted is 1024, change the parameter value to 1024.
Improvement Method
Uint8_t buffer [1024]; NSString * toSend = @ "Welcome to access port 5076"; memcpy (buffer, [toSend UTF8String], 1024); CFWriteStreamWrite (stream, buffer, 1 + strlen (const char *) buffer ));
After testing, the client can display Chinese characters normally.
PS: I have learned about using Socket to transmit data on IOS over the past few days. I will write a complete summary.