简体   繁体   English

使用Java URLConnection的多个TCP连接

[英]Several TCP connections with java URLConnection

I have made a simple HTTP client, which downloads a set of URLs parsed from a webpage. 我做了一个简单的HTTP客户端,它下载了从网页解析的一组URL。

My problem is that the download is slow, compared to a real browser (IE, Firefox, Chrome). 我的问题是,与真正的浏览器(IE,Firefox,Chrome)相比,下载速度较慢。 Especially if the page contains many objects. 特别是在页面包含许多对象的情况下。

I noticed (with wireshark) that many times the real browsers will setup 5-10 TCP connections within the same millisecond instantly after starting the load of a page. 我注意到(使用Wireshark)很多时候,真正的浏览器会在开始加载页面后的同一毫秒内立即建立5-10个TCP连接。 Those conections will then live concurrently for a period of time. 这些连接将同时存在一段时间。

My client will also setup concurrent TCP-connections (and it will reuse TCP connections), but not at all this aggressively. 我的客户端还将建立并发的TCP连接(它将重用TCP连接),但一点也不积极。 I'm guessing that this is one of the reasons my client is slower. 我猜这是我的客户比较慢的原因之一。

I have tried creating several URLConnections before reading from the input stream, but this does not work for me. 我尝试从输入流中读取之前创建多个URLConnections,但这对我不起作用。 I am inexperienced though, so I probably do it wrong. 我没有经验,所以我可能做错了。

Does anyone know of way to do this (mimic what the browsers are doing in terms of TCP connection setup) with URLConnection? 有谁知道用URLConnection做到这一点的方法(模仿浏览器在TCP连接设置方面的工作)吗?

I recommend using HttpClient: 我建议使用HttpClient:

http://hc.apache.org/httpcomponents-client-ga/ http://hc.apache.org/httpcomponents-client-ga/

It has support for internal connection management, pooling etc. Browsers tend to have this sort of stuff. 它支持内部连接管理,池化等。浏览器往往具有此类内容。

Things may have changed since I last used it, but UrlConnection didn't work well for production apps. 自从我上次使用它以来,情况可能已经发生了变化,但是UrlConnection在生产应用程序上无法正常工作。 Ex. 例如 it didn't have a clean way to shut it down. 它没有干净的方法将其关闭。

I would also recommend using a high performance networking library, like Apache Mina . 我还建议使用高性能的网络库,例如Apache Mina This will automatically create thread pool for you and save you a lot of time. 这将自动为您创建线程池并节省大量时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM