我正在构建我的iPhone应用程序的问题。该应用程序向python服务器发送JSON请求,然后从服务器读取JSON响应。我有以下函数将数据发送到服务器并获取响应并将其放入NSData。 (我拿出了帖子的服务器地址)
+(NSData *)accessServer:(NSMutableDictionary *) dic needResponse:(BOOL) response
{
// Conect to the server
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStringRef remoteHost = CFSTR("");
CFStreamCreatePairWithSocketToHost(NULL, remoteHost, 5687, &readStream, &writeStream);
CFWriteStreamOpen(writeStream);
CFReadStreamOpen(readStream);
// send data
NSData *json = [NSJSONSerialization dataWithJSONObject:dic options:0 error:nil];
NSString *jsonString = [[NSString alloc]initWithData:json encoding:NSUTF8StringEncoding];
jsonString = [NSString stringWithFormat:@"%@%@", jsonString, @"\r\n\r\n"];
UInt8 *writeBuf = (UInt8 *)[jsonString UTF8String];
int writtenBytes = 0;
int bytesToSend = (int)[jsonString lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
while(writtenBytes < bytesToSend)
{
writtenBytes += CFWriteStreamWrite(writeStream, writeBuf, bytesToSend-writtenBytes);
}
NSLog(@"Done sending, Sent :%d Total: %d",writtenBytes,bytesToSend);
CFWriteStreamClose(writeStream);
if(response)
{
// get the return data
uint8_t readData[10000];
int readBytes = 1;
int totalRead = 0;
while(readBytes > 0)
{
readBytes = (int)CFReadStreamRead(readStream, readData, 10000);
totalRead += readBytes;
}
CFReadStreamClose(readStream);
return [[NSData alloc]initWithBytes:readData length:totalRead];
}
else
{
CFReadStreamClose(readStream);
return nil;
}
}
问题在于,当我尝试获取NSData并将其转换为NSString时,它的长度为0,NSData的长度为&gt; 0.以下代码是我如何获取NSData并将其转换为NSString。
NSData *t = [Globals accessServer:getLocationData needResponse:TRUE];
NSString *tempString = [[NSString alloc]initWithData:t encoding:NSUTF8StringEncoding];
这个问题似乎发生在大约10%的时间。有时它不会发生一个小时,有时它会连续发生10次。任何帮助表示赞赏,如果您需要我可能忘记了的更多信息,请告诉我。