我在下面的代码处理我的服务器使用套接字发送的响应:
uint8_t buffer[4096];
int len;
NSMutableString *total = [[NSMutableString alloc] init];
while ([inputStream hasBytesAvailable]) {
len = (int)[inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {
NSLog(@"Buffer: %s",buffer);
[total appendString: [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding]];
NSLog(@"Receive: %@, len: %d",total,len);
NSLog(@"len: %d, receive: %@",len,total);
}
}
我的服务器发送如下文本文件:
[{"name_user":"stack overflow","user_key":"XXXXXXX","type":21}]
此代码的问题是,如果我发送JSON,控制台日志会显示该JSON的长度。但如果我发送以下JSON:
[[{"name_user":"stack overflow","user_key":"XXXXXXX","type":21}],[{"name_user":"lacrifilm","user_key":"XXXXXXX","type":21}]]
表示控制台日志显示的JSON中的两个值:
Buffer: ~
Receive: ~
len: 184, receive: ~
我认为问题不在我的服务器中,因为如果是这样的话,我会得到:Receive: ~, len: 184
,而不是Receive: ~
而不是len: 184
正如我们在第二次调用{{}}中看到的那样{1}}在上面的命令中。
我该如何解决这个问题?
答案 0 :(得分:2)
您正在错误地构建字符串。您正在读取一系列字节,而不是字符串。因此,建立NSString
,然后在获得所有数据后创建uint8_t buffer[4096];
NSMutableData *data = [[NSMutableData alloc] init];
while ([inputStream hasBytesAvailable]) {
NSInteger len = [inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {
//NSLog(@"Buffer: %s",buffer); // can't do this - buffer isn't a null-terminated C-string
[data appendBytes:buffer length:len];
NSLog(@"Receive: %@, len: %d", data, (int)len);
}
}
NSString *total = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Total: %@", total);
。更像这样:
BrowserMobProxyServer proxy = new BrowserMobProxyServer();
try {
proxy.start(Integer.valueOf(proxyPool.borrowProxyPort()), InetAddress.getLocalHost());
} catch (NumberFormatException | UnknownHostException e) {
Logger.error(e.getLocalizedMessage());
}
proxy.waitForQuiescence(30, 3, TimeUnit.SECONDS);
proxy.setHarCaptureTypes(CaptureType.REQUEST_HEADERS);
Logger.info("Proxy start status: " + proxy.isStarted());