JavaUser Code: A Little Socket App

User Code: A Little Socket App

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Here is a small socket application developed in Java.
This application has a
simple WebServer, Proxy Server and a Cascading Proxy Server.

http.useproxy=true
http.proxyhost=131.107.2.240
http.proxyport=88

import java.io.*;
import java.net.*;
import java.util.*;

/**
 *   Description: This is an simple java class file which
 *   has an small WebServer, Cascading Proxy Server
 *   and an Proxy Server in built which will serve
 *   only for "http://" protocol.It can act as
 *   an Internet connection sharer for multiple
 *   systems inside a LAN.This is not for 
 *   commercial use.Make sure that you have an
 *   single internet connection from the machine 
 *   from where you are running this application.
 *
 *   The author can be contacted at kalyan.kumar@onebox.com
 *
 *   Important note:
 *  (<-->)For httpd.class to run sucessfully search for String docroot
 *   and set your own document root. Note that http.properties file should be
 *   in the directory from which your are running this class file.WebServer 
 *   in this application supports.html,.gif,.jpeg file extentions.
 *
 *   Author:--> R.KalyanKumar
 *   Dated :--> 9th-May-2001 
 *   
 *   Warranty: Author accepts no responsibility for errors in application. No warranty
 *   is implied or assumed. May not be used for commercial purposes.    
 *
 *   Type "java http" and  to start the application
 *   Type  to terminate this application
 *
 *  Happy Browsing
 **/

public class http implements Runnable
{
	ServerSocket httpSocket=null;
	Socket httpAcceptSock=null;
	Properties env=new Properties();
	FileInputStream fis=null;
	String externalProxyHost="";
	int externalProxyport=80;
					  
	static {
		byte b[]=new byte[2048];
		byte r[]=new byte[1];
	}
	
	public http() {
		new httpd(8400).start();
		////you can change this port '8400' for your convenience
	}
	
	
	public void run() {
		try
		{
			httpSocket=new ServerSocket(8200);//you can change this port '8200' for your convenience
			p("8200->Proxy Server Running!");
			env.load(fis=new FileInputStream("http.properties"));
			//make sure http.properties file is in the directory where this application is running
			Boolean useProxy=new Boolean(env.getProperty("http.useproxy").trim());
			boolean usepxy=useProxy.booleanValue();
			
	
			while(true) {
				httpAcceptSock=httpSocket.accept();
				p("Accepted Connection from "+httpAcceptSock.getInetAddress().getHostName());
			if(usepxy==true) {
				externalProxyHost=(String)env.getProperty("http.proxyhost").trim();
				String pport=(String)env.getProperty("http.proxyport");
				externalProxyport=Integer.parseInt(pport);
				(new Thread(new phttp(externalProxyHost,externalProxyport,httpAcceptSock))).start();
				p("Using external PROXY");
			}
			else
			{
				(new Thread(new WWWListener(httpAcceptSock))).start();
				p("Direct Connect to WWW");
			}
			}
		}catch(Exception err) {
			//err.printStackTrace();
		}
	}
	
	public void p(Object o) {
		System.out.println(o.toString());
	}
	
	public static void main(String args[]) {
		http h=new http();
		Thread th=new Thread(h);
		th.start();
	}
}


class phttp implements Runnable {
	String phost;
	int pport;
	Socket s;
	InputStream in,in1;
	OutputStream out,out1;
	int read;
	Socket httpProxyAcceptSock=null;
	byte b[]=new byte[2048];
	byte r[]=new byte[1024];
	
	phttp(String phost,int pport,Socket s) {
		this.phost=phost;
		this.pport=pport;
		this.s=s;
	}
	
	public synchronized void run() {
		try
		{
			httpProxyAcceptSock=new Socket(phost,pport);
			out1=httpProxyAcceptSock.getOutputStream();
			in1=httpProxyAcceptSock.getInputStream();
			readRequest();
		}catch(Exception err) {
			//err.printStackTrace();
		}
	}
	
	public void readRequest() {
		try
		{
			in=s.getInputStream();
			
			while((read=in.read(r))>0) {
				out1.write(r,0,read);
				
				out1.flush();
				(new httpResponse(s.getOutputStream(),in1,new String(r,0,read))).start();
				if(read<=0) break;
			}
		}catch(Exception err) {
			//err.printStackTrace();
		}
	}
	
	class httpResponse extends Thread
	{
		OutputStream o;
		InputStream i;
		int re;
		String tocache;
		httpCache cache=new httpCache();
		
		httpResponse(OutputStream o,InputStream i,String tocache){
			this.o=o;
			this.i=i;
			this.tocache=tocache;
		}
		
		public synchronized void run() {
			try
			{
				if(cache.isInCache(tocache)) {
					o.write(cache.serveFromCache(tocache),0,cache.serveFromCache(tocache).length);
					o.flush();
				}
				else {
					while((re=i.read(b))>0) {
						o.write(b,0,re);
						cache.cache(tocache,b);						
						o.flush();
						if(re<=0) break;
					}
				}
				o.close();
				i.close();
				s.close();
			}catch(Exception err) {
				//err.printStackTrace();
			}
		}
	}
}

class WWWListener implements Runnable {
	Socket s,httpProxyAcceptSock=null;
	byte onebyte[]=new byte[1024];
	InputStream i_s,http_pi;
	OutputStream o_s,http_po;
	byte b[]=new byte[2048];	
	int r,r1;
	StringBuffer sb=new StringBuffer();
	StringBuffer sb1=new StringBuffer();
	String wwwHost="";
	int port;
	String m;
	
	
	WWWListener(Socket s) {
		this.s=s;
		try
		{
			o_s=s.getOutputStream();
			i_s=s.getInputStream();
		}catch(Exception err) {
			//err.printStackTrace();
		}
	}
	public synchronized void run() {
		try
		{
			while((r=i_s.read(onebyte))>0)
			{
				sb.append(new String(onebyte,0,r));
				sb1.append(new String(onebyte,0,r));
				
				String www_host=parseRequest(sb1.toString());
				StringTokenizer addport=new StringTokenizer(www_host,":");
				String dummy=addport.nextToken();
				String address=addport.nextToken();
				try
				{
					m=addport.nextToken();		
				}catch(NoSuchElementException err){
					port=80;
				}
				if(m!=null) {
					port=Integer.parseInt(m.trim());
				}
				else
				{
					port=80;
				}
				httpProxyAcceptSock=new Socket(address.trim(),port);
				System.out.println("Remote Host:"+httpProxyAcceptSock.getInetAddress().getHostName());
				http_po=httpProxyAcceptSock.getOutputStream();
				http_pi=httpProxyAcceptSock.getInputStream();
				http_po.write(sb.toString().getBytes(),0,sb.toString().length());
				http_po.flush();
				(new httpWWWResponse(http_pi,o_s,sb.toString())).start();
				if(r<=0) break;
			}
		}catch(Exception err) {
			//err.printStackTrace();
		}
	}
	
	public String parseRequest(String rs) {
		System.out.println("REQUEST");
		StringTokenizer tok=new StringTokenizer(rs,"n");
		while(tok.hasMoreTokens()) {
			String tk=tok.nextToken();
			//System.out.println(tk);
			if(tk.startsWith("Host: ")) {
				wwwHost=tk;
			}
		}
		return wwwHost;
	}
	
	class httpWWWResponse extends Thread
	{
		InputStream i;
		OutputStream o;
		int rd;
		String tocache;
		httpCache cache=new httpCache();
		
		httpWWWResponse(InputStream i,OutputStream o,String tocache) {
			this.i=i;
			this.o=o;
			this.tocache=tocache;
		}
		
		public synchronized void run() {
			try
			{
				if(cache.isInCache(tocache))
				{
					o.write(cache.serveFromCache(tocache),0,cache.serveFromCache(tocache).length);
					o.flush();
				}
				else
				{
					while((rd=i.read(b))>0) {
						o.write(b,0,rd);
						o.flush();
						cache.cache(tocache,b);
						if(rd<=0) break;
					}
				}
				o.close();
				i.close();
				s.close();
				httpProxyAcceptSock.close();
			}catch(Exception err) {
				//System.err.println(err);
			}
		}
	}
}


class httpCache extends Hashtable
{
	String s;
	byte[] b=new byte[2048];
	
	httpCache() {
		
	}
	
	public void cache(String s,byte[] b) {
		this.s=s;
		this.b=b;
		super.put(s,b);
	}
	
	public byte[] serveFromCache(String s) {
		this.s=s;
		byte  cas[]=super.get(s).toString().getBytes();
		System.out.println("Served from cache for REQUEST:n"+s);
		return cas;
	}
	
	public boolean isInCache(String s) {
		this.s=s;
		return super.containsKey(s);
	}
}

class httpd extends Thread {

	int serverport;
	ServerSocket srv;
	Socket scli;
	InputStream in;
	OutputStream out;
	boolean hrun=false;
	String docroot="f://html/";// set your own document root here

	public httpd(int serverport) {
		this.serverport=serverport;
		try
		{
			srv=new ServerSocket(serverport);
			System.out.println(serverport+"->WebServer Running!");
			
		}catch(Exception err) {
			//err.printStackTrace();
		}
	}

	public synchronized void run() {
		try
		{
			while(true) {
				scli=srv.accept();
				BufferedReader in=new BufferedReader(new InputStreamReader(scli.getInputStream()));
				String reqDoc=in.readLine();
				String r1=reqDoc.substring(reqDoc.indexOf(" "),reqDoc.lastIndexOf(" "));
				System.out.println(r1);
				if(r1.trim().startsWith("http://")) {
					URL u=new URL(r1);
					String r2=docroot+u.getFile().trim();
					System.out.println("Request on "+serverport+" :"+docroot+r2);
					new httpdResponse(scli,r2).start();
				}
				else
				{
					System.out.println("Request on "+serverport+" :"+docroot+r1.trim());
					String r2=docroot+r1.trim();
					new httpdResponse(scli,r2).start();
				}
			}
		}catch(Exception err) {
			System.out.println("WebServer Error:"+err);
		}
	}

	class httpdResponse extends Thread {

		Socket s;
		String rqdoc;

		httpdResponse(Socket s,String rqdoc) {
			this.s=s;
			this.rqdoc=rqdoc;
			try
			{
				out=s.getOutputStream();
			}catch(Exception err) {
				System.out.println("could not respond:"+err);
			}
		}

		public synchronized void run() {
			try
			{
				File f=new File(rqdoc);
				int filelength=(int)f.length();
				byte b[]=new byte[filelength];
				FileInputStream fis=new FileInputStream(f);
				fis.read(b,0,b.length);
				out.write(b,0,b.length);
				out.flush();
				System.out.println(b.length+" bytes transferred to "+s.getInetAddress().getHostName());
				out.close();
				fis.close();
			}catch(Exception err) {
				try
				{
					PrintWriter pw=new PrintWriter(s.getOutputStream());
					pw.println("<body><font color=red><center>Requested Document Not Found</center></font></body>");
					pw.flush();
					pw.close();
					System.out.println("respond run:"+err);
				}catch(Exception er) {
				}
			}
		
		}
	}
}

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories