gpt4 book ai didi

java - Java 中的代理输入/输出流问题

转载 作者:太空宇宙 更新时间:2023-11-04 08:43:12 25 4
gpt4 key购买 nike

一段时间以来,我一直在尝试一些不同的方法来让我的自定义代理正常工作,到目前为止我能够做到的唯一方法是使用 Apache 的 HttpClient。然而,为了了解,我想知道为什么我自己的代理句柄实现遇到问题:


public void processProxyRequest (Socket client, String request) throws Exception {

if ( !request.equals("") ) {

String[] requestHeaders = request.split("\\r\\n");
Pattern p = Pattern.compile("([A-Z]*)\\s*([^:\\/]*):\\/\\/([^\\s]*)\\s*(?:HTTP.*)");
Matcher m = p.matcher(requestHeaders[0]);

if ( m.matches() ) {
String method = m.group(1).toUpperCase();
String proto = m.group(2).toLowerCase();
String[] requestInfo = m.group(3).split("\\/", 2);

String host = requestInfo[0];
host = ( host.split("\\.").length < 3 ) ? "www." + host : host;
String page = "/";
if ( requestInfo.length == 2 && !requestInfo[1].equals("") ) {
page += requestInfo[1];
}

int remotePort = 80;

if ( proto.equals("https") ) {
remotePort = 443;
}
else if ( proto.equals("ftp") ) {
remotePort = 21;
}
this.sendAndReceive(client, request, host, remotePort);
}
}

}

public void sendAndReceive (Socket client, String request, String host, int port) throws Exception {
Socket target = new Socket(host, port);
System.out.println("Connected to server");

ByteArrayInputStream inStream = new ByteArrayInputStream(request.getBytes());

this.inToOut(inStream, target.getOutputStream());
System.out.println("Sent");
this.inToOut(target.getInputStream(), client.getOutputStream());
System.out.println("Received");
target.close();
}

public void inToOut (InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[1024]; // Adjust if you want
int bytesRead;
System.out.println("reading");
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}

简而言之(并忽略我的请求 header 解析缺陷),上面的代码可以编译并运行,但是,inToOut() 方法似乎有点困难并在 input.read() 期间锁定,我不太清楚为什么。我确实知道我传入的原始套接字是有效的并且打开时没有错误。此外,inToOut() 函数中的 System.out 确实会打印“reading”,但永远不会超过 read() 部分。

谢谢您的建议!

最佳答案

这不是编写代理的方法。对于 HTTP,您只需处理第一行,它告诉您目标主机。其他一切都只是来回复制字节,需要进行一些小的改进,例如正确报告上游连接错误和正确处理关闭。 FTP 的情况比较棘手,应该完全单独处理,但是一旦过了连接阶段,它只是复制字节。您理解该协议(protocol)的努力越少,它就会变得越简单、越好。

关于java - Java 中的代理输入/输出流问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4860044/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com