HTTP Server
import java.net.*;
import java.io.*;
public class WebServe
{
static String getPath(String msg)
{
if (msg.length() == 0 || msg.substring(0,3) == "GET") return null;
String path = msg.substring(msg.indexOf(' ')+1);
path = path.substring(0, path.indexOf(' '));
if (path.equals("")) return "index.html";
if (path.charAt(path.length()-1) == '/') path += "index.html";
return path;
}
static void fileFoundHeader(PrintStream os, int filelength)
{
os.print("HTTP:/1.0 200 OK\n");
os.print("Content-type: text/html\n");
os.print("Content-length: "+filelength+"\n");
os.print("\n");
}
static void sendReply(PrintStream os, DataInputStream in, int flen)
{
try
{
byte buffer[] = new byte[flen];
in.readFully(buffer);
os.write(buffer, 0, flen);
in.close();
}
catch (Exception e) { System.out.println(e); }
}
static void errorHeader(PrintStream os, String err_message)
{
os.print("HTTP:/1.0 404 Not Found\n");
os.print("Content-type: text/html\n");
os.print("Content-length: "+err_message.length()+"\n");
os.print("\n");
os.print(err_message+"\n");
}
static File OpenFile(String filename)
{
File file = new File(filename);
if (file.exists()) return file;
if (filename.charAt(0) != '/') return file;
return new File(filename.substring(1));
}
public static void main(String arg[])
{
String path, a; DataInputStream in, is; PrintStream os;
try
{
ServerSocket server = new ServerSocket(8080);
while (true)
{
Socket client = server.accept();
String destname = client.getInetAddress().getHostName();
System.out.println("Connect:"+client.getInetAddress());
os = new PrintStream(client.getOutputStream());
is = new DataInputStream(client.getInputStream());
String il = is.readLine();
System.out.println("Got:\t"+il);
while (true)
{
a = is.readLine();
if (a.equals("")) break;
System.out.println("\t"+a);
}
System.out.println("----------------------------");
if ((path = getPath(il)) != null)
{
File file = OpenFile(path);
if (file.exists())
{
try
{
in = new DataInputStream(new FileInputStream(file));
fileFoundHeader(os, (int)file.length());
sendReply(os, in, (int)file.length());
}
catch (Exception e) {
errorHeader(os, "< h2>Can't Read "+path+"< /h2>");
}
os.flush();
}
else
errorHeader(os, "< h2>Not Found "+path+"< /h2>");
}
client.close();
}
}
catch (IOException e) { System.out.println(e); }
}
}