我在我的 java 网络服务器和 iOS 应用程序之间来回发送数据。当我发送单个请求时,它工作正常。但是,当我从 iPhone 发送 10 个请求(我的 UITableView 中的每个单元格需要唯一信息)时,该请求无法正常工作。让我解释一下发生了什么:
我的 iOS 应用程序正在使用从服务器返回的数据创建一个 NSData 对象。我正在使用该[NSJSONSerialization JSONObjectWithData]
方法将其转换为 NSDictionary。我收到一条错误消息,指出最后有垃圾数据。当我检查缓冲区时,我看到我的第一个 JSON 字符串进来了,但是下一个 JSON 字符串也附加到它上面。
我如何解决我的服务器在一个字符串中发回请求的问题(因为它处理它的速度如此之快)。
我正在使用 Apple 的 NSStream 类来处理通信。
中的一些代码 -
`(void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent:`
case NSStreamEventHasBytesAvailable:
{
//can read input
if (theStream == inputStream) {
if (inputStream.hasBytesAvailable) {
uint8_t buf[4096];
unsigned int len = 0;
len = [inputStream read:buf maxLength:4096];
if(len > 0 && len < 4096) {
NSError *error;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[NSData dataWithBytes:buf length:len] options:NSJSONReadingAllowFragments error:&error];
if (error) {
当我检查错误时,它最后说垃圾。当请求如下所示时,我收到一个错误:
{"command":"PROFESSOR_RATING","error":false,"data":[{"professor":"Abbott, Philip C","overall":2,"reviews":21}]}{"command":"PROFESSOR_RATING","error":false,"data":[{"professor":"Abel, Gavin Paul","overall":0,"reviews":0}]}{"command":"PROFESSOR_RATING","error":false,"data":[{"professor":"Abel, Steven Richard","overall":5,"reviews":1}]}{"command":"PROFESSOR_RATING","error":false,"data":[{"professor":"Abney, Scott A","overall":0,"reviews":0}]}{"command":"PROFESSOR_RATING","error":false,"data":[{"professor":"Abraham, Dulcy M","overall":0,"reviews":0}]}{"command":"PROFESSOR_RATING","error":false,"data":[{"professor":"Abraham, John ","overall":0,"reviews":0}]}{"command":"PROFESSOR_RATING","error":false,"data":[{"professor":"Abramova, Inna ","overall":0,"reviews":0}]}{"command":"PROFESSOR_RATING","error":false,"data":[{"professor":"Abu-Omar, Mahdi M","overall":0,"reviews":0}]}{"command":"PROFESSOR_RATING","error":false,"data":[{"professor":"Acharya, Lalatendu ","overall":0,"reviews":0}]}{"command":"PROFESSOR_RATING","error":false,"data":[{"professor":"Acosta, Glen G","overall":0,"reviews":0}]}
而不是像这样的单个请求:
{"command":"PROFESSOR_RATING","error":false,"data":[{"professor":"Abbott, Philip C","overall":2,"reviews":21}]}
{"command":"PROFESSOR_RATING","error":false,"data":[{"professor":"Abel, Gavin Paul","overall":0,"reviews":0}]}
..等等
如何将其拆分为每个 JSON 字符串?我有哪些选择?我是否需要更改服务器发送数据的方式?
服务器:
String request = commands[1];
String results = submitReview(request);
bw.write(results);
bw.flush();
我已经尝试手动解析它,但是当我有一个完整的请求(一个有效的 JSON 字符串)时遇到问题,附加一个 LONG Json 字符串(这是无效的,因为它不适合缓冲区,其余的将是在下一个 inputStream 事件中发送))。有没有人有什么建议?
非常感谢。
-卡姆兰