我正在尝试编写一个 Java HTTP 代理隧道程序,并且我需要专家关于用于通信的最佳和最快流的建议。
我已经实现了基本功能,一切正常。唯一的问题是通信速度或性能。我的 HTTP 代理系统由一个在远程服务器上运行的服务器程序和一个在本地机器上运行的客户端程序组成。到目前为止,该程序如下所示:
监听器.java:
/**
* Listens and accepts connection requests from the browser
*/
ServerSocket listener = null;
try {
listener = new ServerSocket(port, 128);
} catch (IOException ex) {
ex.printStackTrace(System.err);
}
ExecutorService executor = Executors.newCachedThreadPool();
Socket connection;
while (!shutdown) {
try {
connection = listener.accept();
executor.execute(new ProxyTunnel(connection));
} catch (IOException ex) {
ex.printStackTrace(System.err);
}
}
代理隧道.java:
try {
byte[] buffer = new byte[8192]; // 8-KB buffer
InputStream browserInput = browser.getInputStream();
OutputStream browserOutput = browser.getOutputStream();
// Reading browser request ...
StringBuilder request = new StringBuilder(2048);
do {
int read = browserInput.read(buffer);
logger.log(read + " bytes read from browser.");
if (read > 0) {
request.append(new String(buffer, 0, read));
}
} while (browserInput.available() > 0 && read > 0);
// Connecting to proxy server ...
Socket server = new Socket(SERVER_IP, SERVER_PORT);
server.setSoTimeout(5000); // Setting 5 sec read timeout
OutputStream serverOutput = server.getOutputStream();
InputStream serverInput = server.getInputStream();
// Sending request to server ...
serverOutput.write(request.toString().getBytes());
serverOutput.flush();
// Waiting for server response ...
StringBuilder response = new StringBuilder(16384);
do {
try {
read = serverInput.read(buffer);
} catch (SocketTimeoutException ex) {
break; // Timeout!
}
if (read > 0) {
// Send response to browser.");
response.append(new String(buffer, 0, read));
browserOutput.write(buffer, 0, read);
browserOutput.flush();
}
} while (read > 0);
// Closing connections ...
server.close();
} catch (IOException ex) {
ex.printStackTrace(System.err);
} finally {
try {
browser.close();
} catch (IOException ex) {
ex.printStackTrace(System.err);
}
}
服务器程序使用类似的方式将 HTTP 请求发送到目标服务器(例如 www.stackoverflow.com)并将响应转发给客户端程序,客户端程序将响应转发给本地浏览器。
- 如何提高这些 TCP/HTTP 通信的性能?
- 是否使用缓冲流等
BufferedInputSream
并BufferedOutputStream
提高通信性能? - 如果我使用
java.nio
Channels 和 Buffers 而不是java.net
Sockets 和java.io
Stream,我会获得任何性能改进吗?