I'm creating a simple proxy server that is multi-threaded and will bypass all the host in the host array.
Please help me to my code.
I only want to use socket and streams for this:
import java.io.*; import java.net.*; import java.util.*; public class ProxyServer extends Thread{ private ServerSocket ss; private String[] host = {"www.google.com", "www.facebook.com"}; private int remotePort = 80; public static long timeout = 30000; public ProxyServer(ServerSocket server) { this.ss = server; } public static void main(String[] args){ try{ System.out.println("Starting the Proxy Server.."); ServerSocket ss = new ServerSocket(50005); System.out.println("Proxy server started at port " + ss.getLocalPort() + ".\r\n"); for(int i = 0; i < 5; i++){ ProxyServer proxy = new ProxyServer(ss); proxy.start(); } }catch(Exception e){ System.out.println(e); } } public void run(){ try{ Socket clientSocket = ss.accept(); InputStream clientIn = clientSocket.getInputStream(); OutputStream clientOut = new BufferedOutputStream(clientSocket.getOutputStream()); for(int i = 0; i < host.length; i++){ try{ Socket serverSocket = new Socket(host[i], remotePort); System.out.println("Open connection to: " + serverSocket + "(timeout= " + timeout + " ms)\r\n"); InputStream serverIn = serverSocket.getInputStream(); OutputStream serverOut = new BufferedOutputStream(serverSocket.getOutputStream()); OpenConnection oc = new OpenConnection(clientIn, serverIn, clientOut, serverOut, clientSocket, serverSocket); oc.run(); }catch(Exception e){ System.out.println(e); } } }catch(Exception e){ System.out.println(e); } } }
import java.io.*; import java.net.*; import java.util.*; public class OpenConnection extends Thread{ InputStream clientIn; InputStream serverIn; OutputStream clientOut; OutputStream serverOut; Socket clientSocket; Socket serverSocket; int timeout = 30000; public OpenConnection(InputStream clientIn, InputStream serverIn, OutputStream clientOut, OutputStream serverOut, Socket c, Socket s) { this.clientIn = clientIn; this.serverIn = serverIn; this.clientOut = clientOut; this.serverOut = serverOut; this.clientSocket = c; this.serverSocket = s; } public void run(){ int r0 = -1, r1 = -1, ch = -1, i = -1; long time0 = new Date().getTime(); long time1 = new Date().getTime(); try{ while(r0 != 0 || r1 != 0 || (time1 - time0) <= timeout) { while((r0 = clientIn.available()) > 0) { ch = clientIn.read(); if(ch != -1) { serverOut.write(ch); System.out.print((char)ch); } time0 = new Date().getTime(); serverOut.flush(); } while((r1 = serverIn.available()) > 0) { try{ ch = serverIn.read(); if(ch != -1) { clientOut.write(ch); } time0 = new Date().getTime(); clientOut.flush(); }catch(Exception e){ } } } }catch(Exception e){ System.out.println(e); }finally{ try{ clientIn.close(); clientOut.close(); serverIn.close(); serverOut.close(); clientSocket.close(); serverSocket.close(); }catch(Exception e){ System.out.println(e); } } } }