我正在开发一个将http流量分成两个设备的应用程序。因此,设备A向网页上的特定资源(图像)发送HEAD请求,然后设备A下载其中一些资源,而设备B下载剩余资源。
这样做的目的是尝试更快地显示网页。然而,有些事情让我感到困惑:
我现在正在测试的两个设备运行速度大致相同(6-8mbps)。它们使用相同的代码下载资源,远程设备(设备B)明显慢于本地设备(A)。
以下是两个设备用于下载资源的代码:
try {
this.timeStarted = System.currentTimeMillis();
Log.d("SIML", "Started downloading HTTP resource: " + urlToDownload);
// Set properties of the connection and connect to the resource
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//conn.setConnectTimeout(5000);
conn.setReadTimeout(10000);
//conn.setRequestProperty("Connection", "close");
//HttpURLConnection.setFollowRedirects(true);
conn.connect();
// Get the input stream and write the data to memory
InputStream in = new BufferedInputStream(conn.getInputStream());
ByteArrayOutputStream res = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = in.read(buffer)) != -1) {
res.write(buffer, 0, bytesRead);
}
res.flush();
res.close();
in.close();
// Keep the data in memory
byte[] data = res.toByteArray();
this.downloaded = data;
Log.d("SIML", "Finished downloading a resource (" + urlToDownload
+ ") of length: " + this.downloaded.length + " bytes");
this.timeFinished = System.currentTimeMillis();
}
我创建的时间戳稍后用于计算下载资源所用的时间。 (如果我有n个资源,我会从最早的时间点开始,并将它与最后完成的资源进行比较。这就是下载所有资源所需的总时间)。
但是,当我将时间戳移动到包含整个方法时,我注意到了一些奇怪的东西。这是一个示例时间:
05-20 14:50:35.613: D/timings(28398): LocalBytes = 2345583 local time = 2.625
05-20 14:50:35.613: D/timings(28398): remoteBytes = 379032 remote time = 2.535
正如您所看到的,它们大致同时完成,但本地设备的下载量是字节数的6倍。请记住,下载速度大致相同。那么,当具有相同的带宽时,远程设备(在这种情况下)的速度是本地设备的6倍?
我的初步解释是持久连接(因为设备A创建头部请求,因此在获取资源之前建立连接)但是,发送所有这些头部请求通常只需要200毫秒。在这种情况下,根据我的观察,远程设备通常使用1-3秒来建立连接。有时甚至更多。
我尝试过切换设备(因此设备A充当远程设备,B充当本地设备)但是远程设备也出现了同样的问题。
我注意到的一件事是,如果我在远程设备上运行speedtest(使用speedtest.net应用程序),然后创建资源请求,那么远程时间将大大减少,从而更准确地模仿实际下载速度。
对于文本墙感到抱歉,但您是否知道我可以做些什么来优化HttpUrlConnection的性能?