📄 webserver.java
字号:
import java.io.*;import java.net.*;import java.util.*;import java.awt.*;final class WebServer { static PrintStream ps; static int numServs = 0; public static void main(String agv[]) { /** author of this WebServer: Javatech/hsdm.com. This server is licsenced under the GPL. Please use accordingly. */ WebServer a = new WebServer(); //allows "this" to work to start a new thread. } public WebServer() { try { DataInputStream din = new DataInputStream(new FileInputStream(new File("httpd.conf"))); Properties p = new Properties(); //loading values nessesary to start server p.load(din); int port; int maxServers; port = Integer.parseInt(p.getProperty("port")); maxServers = Integer.parseInt(p.getProperty("maxServers")); ServerSocket ss = new ServerSocket(port); System.out.println("Running Ontech/hsdm.com WebServer Version 2."); while(true) { //makes sure that the webserver does not run out of memory by having too many connections at once. if(numServs<=maxServers) { Socket incoming = ss.accept(); new Thread(new RequestHandler(incoming,port)).start(); numServs++; } } }catch(Exception e){} }}final class RequestHandler implements Runnable{ PrintStream ps; Socket theRequest; DataInputStream in; PrintStream out; //---- Vector assist; String root; String rootDocs; int port; String log; String MODULES; Vector readS; Hashtable out1; Hashtable srm; //---- public RequestHandler(Socket theRequest1,int port1) { port = port1; this.theRequest = theRequest1; assist = new Vector(); } public void run() { ps=WebServer.ps; out1 = new Hashtable(); srm = new Hashtable(); //Responce types and definitions out1.put((Object)"200", (Object)" OK"); out1.put((Object)"404", (Object)" Not Found"); out1.put((Object)"501", (Object)" Method Not Implemented"); try { readS = new Vector(); Properties p; DataInputStream fin = new DataInputStream(new FileInputStream(new File("srm.conf"))); String l; while((l = fin.readLine())!=null) { StringTokenizer st = new StringTokenizer(l); String ext = (String)st.nextElement(); String encode = (String)st.nextElement(); String mod = (String)st.nextElement(); FileTypes f = new FileTypes(); f.extension = ext; f.encoding = encode; f.module = mod; srm.put((Object)ext,(Object)(f)); } out = new PrintStream(theRequest.getOutputStream()); in = new DataInputStream(theRequest.getInputStream()); String read1 = null; String read = ""; boolean post=false; int numGo = 0; int numWent = 0; int numTotBytes = 0; String readPrev = ""; boolean continue1=true; /* the following block of code is used to figure out the arguments the web server sent and to process it. */ while(continue1) { if(read1!=null) { if(read1.charAt(0) != (char)13) { readPrev = read1; } } char read3[] = new char[10000]; int num = 0; read3[num] = (char)in.read(); while(read3[num]!='\n') { read3[++num] = (char)in.read(); } read1 = new String(read3); if(numGo==0) { if(read1.lastIndexOf("POST")>=0) { post = true; } } if(!post) { continue1 = !((read1).startsWith("\r\n")); } else { if(numWent == 0) { if((read1).charAt(0)==(char)13) { numTotBytes=Integer.parseInt(readPrev.substring(readPrev.indexOf(": ")+2,readPrev.indexOf("\015"))); char tot[] = new char[numTotBytes+1]; for(int i =0;i<numTotBytes;i++) { tot[i] = (char)in.read(); } read1 = new String(tot); continue1 = false; } } } numGo++; if(read1!=null) readS.addElement((Object)read1); } StringTokenizer st; if((String)readS.elementAt(0)!=null) read = (String)readS.elementAt(0); st = new StringTokenizer(read); Vector arg2 = new Vector(); int arg1= 0; while (st.hasMoreTokens()) { arg2.addElement((Object)st.nextToken()); arg1++; } String tempLoc; String params; String arg[] = new String[3]; String attemptHost = ""; boolean works = false; String lastString = ""; /* process virtual hosts. */ for(int i = readS.size()-1;i>0;i--) { String t = (String)readS.elementAt(i); if(t.indexOf(": ")>0) { String second = ""; String firstOcc = ""; firstOcc = t.substring(0,t.indexOf(": ")); second = t.substring(t.indexOf(": ")+2,t.length()); if(firstOcc.equals("Host")) { works=true; if(second.indexOf(":")>0) { attemptHost = second.substring(0,second.indexOf(":")); } else { attemptHost = second; } } } } DataInputStream serv = new DataInputStream(new FileInputStream(new File("server.conf"))); String theText = ""; boolean done = false; String file = ""; boolean works1 = false; while((theText = serv.readLine())!=null&&done != true&&works==true) { StringTokenizer stringt = new StringTokenizer(theText,"|"); if(((String)stringt.nextElement()).equals(attemptHost)) { stringt.nextToken(); file = stringt.nextToken(); done = true; works1 = true; } else if(((String)stringt.nextElement()).equals(attemptHost)) { file = stringt.nextToken(); done = true; works1=true; } } if(works1==false) { serv = new DataInputStream(new FileInputStream(new File("server.conf"))); theText = serv.readLine(); StringTokenizer stringt = new StringTokenizer(theText,"|"); stringt.nextToken(); stringt.nextToken(); file=stringt.nextToken(); } DataInputStream din = new DataInputStream(new FileInputStream(new File(file))); p = new Properties(); p.load(din); root = p.getProperty("root"); log = p.getProperty("log"); rootDocs = p.getProperty("rootDocs"); rootDocs = root+"/"+rootDocs; log1.ps = new PrintStream(new DataOutputStream(new FileOutputStream(log,true))); ps = log1.ps; MODULES = p.getProperty("assistants"); st = new StringTokenizer(MODULES,","); while (st.hasMoreTokens()) { assist.addElement((Object)st.nextToken()); } if(arg1>0) { arg[0] = (String)arg2.elementAt(0); } else { error(501); return; } if(arg1>1) { arg[1] = (String)arg2.elementAt(1); } else { error(501); return; } if(arg1>2) { arg[2] = (String)arg2.elementAt(2); } else { error(501); return; } if(arg[1].indexOf("?")>0) { tempLoc = arg[1].substring(0,arg[1].indexOf("?")); params = arg[1].substring(arg[1].indexOf("?")+1,arg[1].length()); } else { tempLoc = arg[1]; params = ""; } tempLoc = rootDocs+tempLoc; File theFile = new File(tempLoc); if(!arg[0].equals("GET")&&!arg[0].equals("POST")) { error(501); } else if(!arg[2].equals("HTTP/1.1")&&!arg[2].equals("HTTP/1.0")) { error(501); } else { int eCode = 0; boolean exists = false; int i1 = 0; String newFile = theFile.getPath(); String theRealString = root; boolean lastDir = false; log(200); if((newFile.charAt(newFile.length()-1)=='/')) { lastDir = true; } newFile = newFile.substring(newFile.indexOf(root)+root.length(),newFile.length()); StringTokenizer st123 = new StringTokenizer(newFile,"/"); int numDepth = 0; while(st123.hasMoreElements()) { String theNextString = st123.nextToken(); if(!theNextString.equals("..")) { numDepth++; theRealString = theRealString+"/"+theNextString; } else { if(numDepth>=0) { numDepth--; } } } if(lastDir){theRealString+="/";} //work with modules. theFile = new File(theRealString); if(!theFile.exists()) {i1 = assist.size();} if(!theFile.canRead()){i1 = assist.size();} boolean worked = false; if(theFile.isFile()) { String ext = theFile.getName().substring(theFile.getName().lastIndexOf("."),theFile.getName().length()); FileTypes e = (FileTypes)srm.get(ext); for(i1 = 0;i1<assist.size();i1++) { basicModule b = (basicModule)getObject((String)(assist.elementAt(i1))); if((((String)assist.elementAt(i1)).equals(e.module))) { worked = true; eCode = 200; i1 = assist.size(); head("200"); if(!(e.encoding).equals("-")) { out.print("Content-type: "+e.encoding+"\r\n"); } b.runFile(theFile,params,(OutputStream)out,readS); } } } else if(theFile.isDirectory()) { Enumeration e = srm.keys(); boolean weAreDone = false; File f = new File(""); while(e.hasMoreElements()&&!weAreDone) { f = new File(theFile.getPath()+"index"+e.nextElement()); if(f.exists()) { weAreDone = true; } } if(weAreDone) { File f1 = new File(f.getPath()); String ext = f1.getName().substring(f1.getName().lastIndexOf("."),f1.getName().length()); FileTypes e1 = (FileTypes)srm.get(ext); String mod = e1.module; basicModule b = (basicModule)getObject(mod); eCode = 200; worked = true; i1 = assist.size(); head("200"); if(!(e1.encoding).equals("-")) { out.print("Content-type: "+e1.encoding+"\r\n"); } b.runFile(f1,params,(OutputStream)out,readS); } } if(!worked) { File thetemp = new File(theFile.getName()); if(!thetemp.exists()) { error(404); } else if(!thetemp.canRead()) { error(403); } else { head("200"); out.print("OK"); DataInputStream tin = new DataInputStream(new FileInputStream(new File(theFile.getName()))); String red; out.println("Content-type: text/html \n\n"); while((red = tin.readLine())!=null) { out.println(red); } } } } out.close(); WebServer.numServs--; }catch(Exception e){ps.print(e.getMessage());out.close();} } public Object getObject(String name) throws Exception { Object obj; Class aClass = Class.forName(name); obj = aClass.newInstance(); return obj; } public void error(int valNum) throws Exception { log(valNum); head(Integer.toString(valNum)); FileTypes e = (FileTypes)srm.get(".html"); out.println("Content-type: "+e.encoding+"\r\n\r\n"); File readFrom = new File(root+"/error/"+valNum+".html"); if(readFrom.exists()) { DataInputStream din = new DataInputStream(new FileInputStream(readFrom)); String read; while((read = din.readLine())!=null) { out.println(read.substring(0,read.length()-2)); } } else { out.println("<HTML><BODY BGCOLOR = \"White\"><B>Error Code "+valNum+"<HR>"); out.println("There is a problem in your request. Also there is no error page for this error. Please contact the Network Administator<HR><ADDRES>Ontech WebServer 2 on port "+port+"</address>"); } } public void head(String sErr) { out.print("HTTP/1.1 "+sErr+" "+out1.get(sErr)+"\r\n"); } public void log(int errCode) { log1.ps.println(errCode+" --["+theRequest.getInetAddress()+"]"); for(int i =0;i<readS.size();i++) { String a = (String)readS.elementAt(i); if(!a.startsWith("\r\n")) log1.ps.println(a.substring(0,a.indexOf((char)13))); } if(ps!=null) log1.ps.println("--"); }}class log1{ public static PrintStream ps; public static void setStream(PrintStream out) { ps = out; } public static void write(String str) { ps.println(str); }}class FileTypes{ String extension; String encoding; String module; String dir;}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -