Created
May 29, 2015 05:38
-
-
Save mishudark/23328b5e530bce5cf669 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.net.*; | |
public class Proxy { | |
int local_port; | |
int destiny_port; | |
String destiny_url; | |
ServerSocket server; | |
Socket proxy; | |
Socket destiny; | |
InputStream from_destiny; | |
OutputStream to_destiny; | |
InputStream from_local; | |
OutputStream to_local; | |
//constructor | |
Proxy() { | |
} | |
public static void main(String[] args){ | |
Proxy client = new Proxy(); | |
client.startProxy(args); | |
} | |
private void startProxy(String[] args){ | |
if(args.length != 3){ | |
System.out.println("Usage: java Proxy local_port destiny_port destiny_url"); | |
return; | |
} | |
try{ | |
//get the ports and destiny from command line | |
local_port = Integer.parseInt(args[0]); | |
destiny_port = Integer.parseInt(args[1]); | |
destiny_url = args[2]; | |
}catch (Exception e) { | |
System.out.println(e); | |
} | |
//open a new socket | |
try{ | |
server = new ServerSocket(local_port); | |
}catch(IOException e){ | |
System.out.println(e); | |
return; | |
} | |
//create space to data | |
byte[] input_data = new byte[4096]; | |
byte[] output_data = new byte[4096]; | |
while(true){ | |
try{ | |
proxy = server.accept(); | |
}catch(IOException e){ | |
System.out.println(e); | |
return; | |
} | |
try{ | |
from_local = proxy.getInputStream(); | |
to_local = proxy.getOutputStream(); | |
}catch(IOException e){ | |
System.out.println(e); | |
return; | |
} | |
try{ | |
destiny = new Socket(destiny_url, destiny_port); | |
}catch (Exception e) { | |
System.out.println(e); | |
return; | |
} | |
try{ | |
from_destiny = destiny.getInputStream(); | |
to_destiny = destiny.getOutputStream(); | |
Thread sync = new Thread() { | |
public void run() { | |
int reader; | |
try { | |
while((reader = from_local.read(input_data)) != -1) { | |
to_destiny.write(input_data, 0, reader); | |
to_destiny.flush(); | |
} | |
to_destiny.close(); | |
} catch (IOException e) {} | |
} | |
}; | |
sync.start(); | |
int writer; | |
while((writer = from_destiny.read(output_data)) != -1) { | |
to_local.write(output_data, 0, writer); | |
to_local.flush(); | |
} | |
to_local.close(); | |
proxy.close(); | |
destiny.close(); | |
}catch(IOException e){ | |
System.out.println(e); | |
return; | |
} | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment