我正在尝试用Java创建一个代理服务器来旋转代理。我的意思是,我正在创建一个代理服务器,将请求传递给另一个随机代理,从该随机代理获取响应并将其返回给客户端。
这样的事情:
我有两个主要的类处理它。第一个类称为RunnableRequestLayer
,它负责读取客户端的请求,并将响应发回。第二个类是RequestMaker
,它连接到随机代理,并且具有从随机代理发送/接收的send()
和receive()
方法。
以下是两个类的相关代码:
第1课:RunnableRequestRelayer
public class RunnableRequestRelayer implements Runnable {
private Socket socket;
private final int maxTries = 5;
public RunnableRequestRelayer(Socket socket) {
this.socket = socket; //This socket is the serverSocket.accept() socket
}
@Override
public void run() {
System.out.println("Got a request!");
try(
PrintWriter out =
new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
){
RequestMaker rm = new RequestMaker();
int tries = 0;
while(tries++ < maxTries){
try{
rm.connect();
} catch(IOException e){
continue;
}
String inputLine;
//This while loop reads the input HttpRequest fine.
while((inputLine = in.readLine()) != null){
if(inputLine.equals(""))
break;
rm.send(inputLine + "\r\n");
//System.out.println(rm.receive());
}
System.out.println("Test"); //This is successfully printing.
String outputLine;
//This output loop is never entered... why?
while((outputLine = rm.receive()) != null){
System.out.println("In output loop");
if(outputLine.equals(""))
break;
out.print(outputLine + "\r\n");
out.flush();
System.out.println(outputLine);
}
rm.disconnect();
tries = maxTries;
}
} catch(IOException e) {
System.out.println("Bad");
}
}
第2课:RequestMaker
public class RequestMaker {
private Socket socket;
PrintWriter out;
BufferedReader in;
public void connect() throws IOException {
String[] proxy = ProxyGenerator.generate().split(":");
socket = new Socket(proxy[0], Integer.parseInt(proxy[1]));
System.out.println("Connected to proxy - " + proxy[0] + ":" + proxy[1]);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
public void send(String s) {
out.write(s);
out.flush();
}
public String receive() throws IOException {
return in.readLine();
}
public void disconnect() {
try{
out.flush();
out.close();
in.close();
socket.close();
} catch(IOException e) {}
}
}
我也试过用fiddler测试这个。我将代理设置为连接到127.0.0.1:8888
,这是Fiddler的代理服务器。再次,请求是从客户端收到的,但Fiddler上的代理从未收到过。
我的问题是:为什么从代理读取的while循环不首先进入?我检查了rm.receive()是否使用if返回""
或null
,而不是。
答案 0 :(得分:0)
原来我没有正确遵循HTTP协议。在将输入请求写入代理服务器后,必须发送空行。