import java.io.*;
import java.net.*;
import java.util.*;
public class j8httpServer {
private static char cPort = 8888;
private static final String sVersion = "j8httpServer/1.0(JVM)";
private static String sHomePage = "index.html";
private static String sLocalPath = "wwwroot";
public static void main(String[] sa) {
getArgument(sa);
ServerSocket ss = null;
try {
ss = new ServerSocket(cPort);
System.out.println(sVersion + " m@20190429.yiyi");
while(true) {
Socket s = ss.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String sLine = br.readLine();
doSwitch(s, sLine.substring(sLine.indexOf('/') + 1, sLine.lastIndexOf('/') - 5));
br.close();
s.close();
}
} catch(Exception e) {
e.printStackTrace();
}
}
private static void doSwitch(Socket s, String sResource) throws Exception {
if(sResource.equals("")) {
sResource = sHomePage;
}
if(sResource.toLowerCase().endsWith(".css")) {
toTransfer(s, "text/css", sResource);
} else if(sResource.toLowerCase().endsWith(".html") || sResource.toLowerCase().endsWith(".htm")) {
toTransfer(s, "text/html", sResource);
} else if(sResource.toLowerCase().endsWith(".js")) {
toTransfer(s, "text/javascript", sResource);
} else if(sResource.toLowerCase().endsWith(".gif")) {
toTransfer(s, "image/gif", sResource);
} else if(sResource.toLowerCase().endsWith(".jpeg") || sResource.toLowerCase().endsWith(".jpg")) {
toTransfer(s, "image/jpeg", sResource);
} else if(sResource.toLowerCase().endsWith(".png")) {
toTransfer(s, "image/png", sResource);
} else {
notFound(s);
}
}
private static void getArgument(String[] sa) {
try {
for(int i = 0; i < sa.length; i++) {
if(sa[i].toLowerCase().startsWith("-port:")) {
int iPort = Integer.valueOf(sa[i].substring(6));
if(iPort >= 0 && iPort < 65536) {
cPort = (char)iPort;
}
} else if(sa[i].toLowerCase().startsWith("-homepage:")) {
sHomePage = sa[i].substring(10);
} else if(sa[i].toLowerCase().startsWith("-localpath:")) {
sLocalPath = sa[i].substring(11);
}
}
} catch(NumberFormatException nfe) {
nfe.printStackTrace();
}
}
private static void notFound(Socket s) throws Exception {
PrintWriter pw = new PrintWriter(s.getOutputStream());
pw.println("HTTP/1.0 404 Not found");
pw.println("Server:" + sVersion);
pw.println("Date:" + new Date());
pw.println();
pw.flush();
pw.close();
}
private static void toTransfer(Socket s, String sContentType, String sRemotePath) throws Exception {
PrintStream ps = new PrintStream(s.getOutputStream());
File f = new File(sLocalPath + File.separator + sRemotePath);
Long l = f.length();
byte[] b = new byte[l.intValue()];
ps.println("HTTP/1.1 200 OK");
ps.println("Content-Type:" + sContentType);
ps.println("Content-Length:" + l);
ps.println("Server:" + sVersion);
ps.println("Date:" + new Date());
ps.println();
FileInputStream fis = new FileInputStream(f);
fis.read(b);
fis.close();
if(sContentType.startsWith("text/")) {
ps.print(new String(b));
} else {
ps.write(b);
}
ps.flush();
ps.close();
}
}