Académique Documents
Professionnel Documents
Culture Documents
this program
can be use as sever which is able to process requsts for html pages.
//httpserver.java
import java.io.*;
import java.net.*;
import java.util.*;
import java.lang.*;
system.out.println("******************************************************
**************************");
system.out.println("****************************** http
server
***********************************");
system.out.println("******************************************************
**************************");
system.out.println("server started...");
system.out.println("waiting for connections...");
try
{
boolean done=false;
while(!done)
{
reqh=in.readline();
if(reqh == null)
done = true;
else
{
//out.println("server>>> " + headerline);
system.out.println(reqh);
}
}
*/
stringtokenizer s = new stringtokenizer(headerline);
string meth = s.nexttoken();
if(meth.equals("get")||meth.equals("post"))
{
int dot1,dot2,fslash;
string fname,ext,filename;
string url = s.nexttoken();
dot1=url.indexof('.');
dot2=url.lastindexof('.');
fslash=url.lastindexof('/');
fname=url.substring(dot1+1,dot2);
ext=url.substring(dot2,fslash);
filename=fname+ext;
// system.out.println("fname:"+filename);
if(ext.equals(".html")||ext.equals(".htm"))
{
fileinputstream fis=null;
boolean filexists=true;
try
{
fis=new fileinputstream(filename);
}
catch(filenotfoundexception e)
{
system.out.println("exception: "+e.getmessage());
filexists=false;
}
if(filexists)
{
statusline=" http/1.1 200 ok"+crlf;
contenttypeline="content-type: text/html "+crlf;
contentlength="content-length:"+(new
integer(fis.available())).tostring() + crlf;
}
else
{
/* system.out.println("
responce header ");
system.out.println(statusline);
system.out.println(venderline);
system.out.println(contentlength);
system.out.println(contenttypeline);*/
output.write(statusline.getbytes());
output.write(venderline.getbytes());
output.write(contentlength.getbytes());
output.write(contenttypeline.getbytes());
output.write(crlf.getbytes());
if (filexists)
{
sendbytes(fis, output) ;
fis.close();
}
else
{
output.write(entitybody.getbytes());
}
}
else
{
statusline = "http/1.0 400 not found" + crlf ;
contenttypeline = "content-type: text/html"+crlf ;
entitybody = "<html>" +
"<head><title>400</title></head>" +
"<body><h1>400 a malformed http request is
reived</h1></body></html>";
}
else
{
statusline = "http/1.0 400 not found" + crlf ;
contenttypeline = "content-type: text/html"+crlf ;
entitybody = "<html>" +
"<head><title>400</title></head>" +
"<body><h1>400 a malformed http request is
reived</h1></body></html>";
}
boolean done=false;
while(!done)
{
headerline=in.readline();
if(headerline == null)
done = true;
else
{
system.out.println(headerline);
}
}
incoming.close();
in.close();
out.close();
}
catch(exception e)
{
system.out.println("error: " + e);
}
}
private static void sendbytes(fileinputstream fis, outputstream os)
throws exception
{
byte[] buffer = new byte[1024] ;
int bytes = 0 ;