Programming a proxy server with Java - How to? [closed]
I have an assignment to write a proxy server with java. I must be able to read and modify http headers and block some sites on a provided black-list.
I have an experience with java, but never worked with http, sockets, connections, ports etc..
Already couple of days trying Google some examples or tutorials, but what I find is either very simple and don't have full capabilities or very very complicated or not working.
Can you help me with some relevant examples开发者_开发技巧, links, tutorials etc...?
I have also to notice, that I found a webpage with an open source proxy servers, but they don't really work or very complicated.
thanks!
Edit:
Hi, I found some code that listens to connections coming from a browser and starts a new thread for every connection.
public class Main {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listening = true;
int port = 10000; //default
try {
port = Integer.parseInt(args[0]);
} catch (Exception e) {
//ignore me
}
try {
serverSocket = new ServerSocket(port);
System.out.println("Started on: " + port);
} catch (IOException e) {
System.err.println("Could not listen on port: " + args[0]);
System.exit(-1);
}
while (listening) {
new ProxyThreadServer(serverSocket.accept()).start();
}
serverSocket.close();
}
}
The part that I'm really confused with is how to transfer the request to a server(URL) , get a response from it and send the response to the browser.
So basically I need a 4 steps:
Listen and get the request from a browser.
Forward the request to the web-server.
Get the response from the web server.
Send the response to the browser.
The extra features is working with the headers and block some connections. But for the start these 4 steps will do fine.
The easiest way is to have a thread accepting new connections on a ServerSocket
. For each connection that it gets (via the accept
call), start off a new thread to handle that connection. Pass the new Socket
that you receive via the accept
call to the new session handling thread. That is the core of the proxy server.
For each of these session handling threads, you need to read the HTTP request from the client and decide what to do with it. You need to determine which HTTP server you are going to contact, then connect to it with a new Socket
object that you create. You can do two-way forwarding between the client and server at that point so your proxy is transparent to either end.
HTTP is a complicated beast so hopefully your assignment is pretty limited in scope, in which case this outline should help you get started.
Hope that helps!
精彩评论