📄 working_server.java
字号:
} System.out.println(" value = "+value); headerArray[j] = name+"="+value; d++; } } } } else{ //handles headers when there is a body from a post request System.out.println("into else"); for (int j=0; j<numEnvVars-3; j++){ value = ""; temp = (String) v.elementAt(d); StringTokenizer pos = new StringTokenizer(temp, ":"); if((pos.hasMoreTokens())){ name = pos.nextToken().trim(); name = "HTTP_"+name.toUpperCase(); System.out.println(" name = HTTP_"+name.toUpperCase()); if(pos.hasMoreTokens()){ value = pos.nextToken().trim(); while(pos.hasMoreTokens()){ value = value + ":" + pos.nextToken().trim(); } System.out.println(" value = "+value); headerArray[j] = name+"="+value; d++; } } } headerArray[numEnvVars-3]=(String)v.lastElement(); } } } public void handleCGI(String fname, String cgiVars) throws IOException { //method which handles incoming cgi requests // System.out.println("Filename: "+ fname + "\r\nCGIVars: " + cgiVars); filepath = _serverConfig.getProperty("server.root") + _serverConfig.getProperty("cgi.root"); System.out.println("Filepath: " + filepath); File f = new File(filepath, fname); filepath = filepath+fname; if ((f.isFile()) && (f.canRead())){ //begin filling the enviroment variables env = new String [numEnvVars]; env[0] = "REQUEST_METHOD="+methodType; env[1] = "QUERY_STRING="+cgiVars; System.out.println("env[0]: "+env[0]); System.out.println("env[1]: "+env[1]); int b = 0; for(int a=2;a<numEnvVars; a++){ env[a]=headerArray[b]; System.out.println("env["+a+"]: "+env[a] ); b++; } if(methodType.equals("GET")){ startCGI(filepath, env, ""); } else if(methodType.equals("POST") && body == true){ //if post request must get the body of the request and store it after validating the request int cl = 0; String x =""; String cleng = "HTTP_CONTENT-LENGTH"; String ct = "HTTP_CONTENT-TYPE=APPLICATION/X-WWW-FORM-URLENCODED"; String rqcleng = env[numEnvVars-2]; String rqct = env[numEnvVars-3]; if(!rqcleng.startsWith(cleng)) { System.out.println("incoming content length: "+rqcleng); System.out.println("should b content length: "+cleng); System.out.println("content length failed"); sendError(400, "Bad POST Request -- Invalid Syntax"); } if(!rqct.regionMatches(true,0,ct,0,rqct.length())){ System.out.println("content type failed"); sendError(400, "Bad POST Request -- Invalid Syntax"); } else{ //Make sure content lengthh is correct System.out.println("Its a Valid Post Request!!!!!!"); StringTokenizer st = new StringTokenizer (rqcleng, "="); if((st.hasMoreTokens()) && (st.countTokens()==2)){ x=st.nextToken().trim(); x=st.nextToken().trim(); cl= new Integer(x).intValue(); } System.out.println("content length supposed to be: "+cl); System.out.println("content length is------------: "+(env[env.length-1].length())); if (cl!=((env[env.length-1].length()))){ sendError(400, "Content length not correct"); } System.out.println("filepath: "+filepath); } startCGI(filepath, env, env[env.length-1]); } } else if(!f.isFile()){ sendError(404, "File not found"); } else if(!f.canRead()){ sendError(403, "Forbidden -- File not readable"); } else{ sendError(500, "Internal Server Error"); } } public void startCGI(String fileName, String [] envs, String postBody) { //method which uns the cgi programs System.out.println("into startCGI"); Process p = null; InputStream out; InputStreamReader isr; BufferedReader br; String s = ""; Vector cgiOut = new Vector(); int a; String [] envVars; byte[] ba = postBody.getBytes(); int m = 1; if (body==true){ String [] ta = new String [envs.length-1]; for (int w = 0; w<envs.length-1; w++){ ta[w] = envs[w]; } envVars = new String [ta.length]; envVars = ta; } else{ envVars = new String [envs.length]; envVars = envs; } try{ System.out.println("running cgi: "+fileName); p = Runtime.getRuntime().exec(fileName,envVars); try{ OutputStream os = p.getOutputStream(); os.write(ba); os.close(); p.waitFor(); m = p.exitValue(); } catch(InterruptedException e){} } catch(IOException i){} // System.out.println("made it out of proccess"); if(m==0){ //cgi exited properly out = p.getInputStream(); isr = new InputStreamReader(out); br = new BufferedReader(isr); try{ while((s=br.readLine())!=null){ System.out.println(s); s=s+"\n"; cgiOut.add(s); } br.close(); isr.close(); out.close(); sent=true; }catch(IOException i){ System.out.println("IOexception"); } // System.out.println("calling sendcgi"); sendCGI(cgiOut); } else{ //cgi did not exit properly try{ sendError(500, "internal Server Error While Running cgi"); }catch(IOException i){ System.out.println("IOexception"); } } } public void sendCGI(Vector c){ //method which sends the results fromthe cgi program String [] tmp = new String [c.size()]; String s = ""; byte[] tempb = new byte[1]; System.out.println("into SendingCGI"); /* for(int i=0; i<c.size(); i++){ tmp[i] = (String) c.elementAt(i); s = s+ tmp[i]; System.out.println("adding"); try{ System.out.println("Sending"); tempb = s.getBytes(); dataToClient.write(tempb); } catch(IOException e){} } _s.close(); */ try{ for(int i=0; i<c.size(); i++){ s = (String) c.elementAt(i); tempb = s.getBytes(); dataToClient.write(tempb); } _s.close(); }catch(IOException e){} } public void sendFile(File rqFile)throws FileNotFoundException, IOException, InterruptedException{ //method which sends static (non cgi) files System.out.println("Sending File: " + rqFile + "\n"); BufferedReader br = new BufferedReader(new FileReader(rqFile)); //FileReader fr = new FileReader(rqFile); String tempLine; byte[] tempb; byte b; Date currentTime = new Date(); // ctype = (String) _mt.get(filetype); headers = "HTTP/"+httpVer + " 200 OK\r\nDate: " + getDate().format(currentTime); headers = headers + "\r\nConnection: Close"; headers = headers + "\r\nContent-Length: " + rqFile.length(); headers = headers + "\r\nContent-Type: " + ctype + "\r\n"; tempb = headers.getBytes(); dataToClient.write(tempb); if(!methodType.equals("HEAD")){ while ((tempLine = br.readLine()) != null) // while ((b=(byte)fr.read()) != -1) { tempb = tempLine.getBytes(); dataToClient.write(tempb,0,tempb.length); //dataToClient.write(b); //_s.flush(); } } _s.close(); sent = true; } public void sendResponse() throws IOException{ //method which sends if nothing else worked if(!sent){ byte [] temp; String st; String err = "<HTML><HEAD><TITLE>Error 500</TITLE></HEAD> "; err = err +"<BODY> <H1>Error: 500 Internal Server Error</H1></BODY></HTML>"; st = "HTTP/1.0 500 Internal Server Error\r\n"; st = st + "Connection: Close \r\n"; st = st + "Content-length: "+ err.length() + "\r\n"; st = st + "Content-type: text/html \r\n"; st = st + err; temp = st.getBytes(); dataToClient.write(temp); st = ""; _s.close(); this.stop(); } sent = true; } public void sendError(int errNum, String errDes) throws IOException{ //method which sends detailed error message System.out.println("Into SendError"); if(!sent){ byte [] temp; String st; String err = "<HTML><HEAD><TITLE>Error " + errNum+ ": "+ errDes+"</TITLE></HEAD> "; err = err +"<BODY> <H1>Error: " +errNum +" " + errDes + "</H1></BODY></HTML>"; st = "HTTP/"+httpVer+" "+errNum+" "+errDes+"\r\n"; st = st + "Connection: Close \r\n"; st = st + "Content-length: "+ err.length() + "\r\n"; st = st + "Content-type: text/html \r\n"; st = st + err; temp = st.getBytes(); dataToClient.write(temp); st = ""; _s.close(); this.stop(); } sent = true; } public void getCT(String rqFile){ //method which gets the content type of files System.out.print("Into Content Type \n"); StringTokenizer st = new StringTokenizer(rqFile,"."); String fname = st.nextToken(); System.out.print("Fname: " + fname + " \n"); String ext = st.nextToken(); System.out.print("Ext: " + ext + " \n"); ctype = (String) _mt.get(ext); } public SimpleDateFormat getDate(){ //method which gets the time String dateFormatString = "EEE, dd MMM yyyy, kk:mm:ss z"; SimpleDateFormat sdf = new SimpleDateFormat(dateFormatString); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); return sdf; } public static void main (String [] args) throws FileNotFoundException, IOException, InterruptedException, NoSuchMethodError { Properties serverConfig = new Properties(); Properties mimeTypes = new Properties(); Hashtable mt = new Hashtable(); // new File(".").getAbsolutePath(); //serverConfig.load(new FileInputStream(new File(".").getAbsolutePath()+"/srm.conf")); //mimeTypes.load(new FileInputStream(new File(".").getAbsolutePath()+"/mime.types")); serverConfig.load(new FileInputStream(new File("src/org/jmule2/middleware/http").getAbsolutePath()+"/srm.conf")); mimeTypes.load(new FileInputStream(new File("src/org/jmule2/middleware/http").getAbsolutePath()+"/mime.types")); int localport = -1; boolean error = false; int defport = new Integer(serverConfig.getProperty("port")).intValue(); String usage = "usage: java working_server [-p]\noptions:\n[-p port number] the port to run on (default port: " + defport +")"; try{ for (int i=0; i<args.length; i++){ if (args[i].equals("-p")){ if (++i>=args.length){ System.err.println(usage); System.exit(1); } localport = new Integer(args[i]).intValue(); // localport = parselocalport.parseInt(args[i], 10); } else{ System.err.println(usage); System.exit(1); } } } catch(NumberFormatException e){ System.err.println("Error: " + e.getMessage() + "\n"); System.exit(1); } /* if(localport <= 0){ System.err.println("Error: Invalid Local Port Specification " + "\n"); error = true; } } if (args.length > 1){ System.err.println("Usage: server <port> \n or server (default port used)"); } if(error) System.exit(-1); if (localport == -1){ localport = new Integer(serverConfig.getProperty("port")).intValue(); } */ if(localport==-1) localport=defport; System.out.println("Starting server on port " + localport); ServerSocket ss = new ServerSocket(localport); while(true) { //loop forever Socket s = ss.accept(); //Blocks waiting for a new connection working_server serv = new working_server(s, serverConfig, mimeTypes, mt); //Create a new child process serv.start(); //Start the child process } } }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -