Java 实现 web服务器的简单实例
Java实现web服务器的简单实例
实例代码:
importjava.util.*;
//Chapter8,Listing3
publicclassWebServerDemo{
//DirectoryofHTMLpagesandotherfiles
protectedStringdocroot;
//Portnumberofwebserver
protectedintport;
//Socketforthewebserver
protectedServerSocketss;
//HandlerforaHTTPrequest
classHandlerextendsThread{
protectedSocketsocket;
protectedPrintWriterpw;
protectedBufferedOutputStreambos;
protectedBufferedReaderbr;
protectedFiledocroot;
publicHandler(Socket_socket,String_docroot)throwsException{
socket=_socket;
//Gettheabsolutedirectoryofthefilepath
docroot=newFile(_docroot).getCanonicalFile();
}
publicvoidrun(){
try{
//Prepareourreadersandwriters
br=newBufferedReader(newInputStreamReader(
socket.getInputStream()));
bos=newBufferedOutputStream(socket.getOutputStream());
pw=newPrintWriter(newOutputStreamWriter(bos));
//ReadHTTPrequestfromuser(hopefullyGET/file......)
Stringline=br.readLine();
//Shutdownanyfurtherinput
socket.shutdownInput();
if(line==null){
socket.close();
return;
}
if(line.toUpperCase().startsWith("GET")){
//Eliminateanytrailing?data,suchasforaCGIGET
//request
StringTokenizertokens=newStringTokenizer(line,"?");
tokens.nextToken();
Stringreq=tokens.nextToken();
//Ifapathcharacter/or/isnotpresent,addittothe
//documentroot
//andthenaddthefilerequest,toformafullfilename
Stringname;
if(req.startsWith("/")||req.startsWith("//"))
name=this.docroot+req;
else
name=this.docroot+File.separator+req;
//Getabsolutefilepath
Filefile=newFile(name).getCanonicalFile();
//Checktoseeifrequestdoesn'tstartwithourdocument
//root....
if(!file.getAbsolutePath().startsWith(
this.docroot.getAbsolutePath())){
pw.println("HTTP/1.0403Forbidden");
pw.println();
}
//...ifit'smissing.....
elseif(!file.exists()){
pw.println("HTTP/1.0404FileNotFound");
pw.println();
}
//...ifitcan'tbereadforsecurityreasons....
elseif(!file.canRead()){
pw.println("HTTP/1.0403Forbidden");
pw.println();
}
//...ifitsactuallyadirectory,andnotafile....
elseif(file.isDirectory()){
sendDir(bos,pw,file,req);
}
//...orifit'sreallyafile
else{
sendFile(bos,pw,file.getAbsolutePath());
}
}
//IfnotaGETrequest,theserverwillnotsupportit
else{
pw.println("HTTP/1.0501NotImplemented");
pw.println();
}
pw.flush();
bos.flush();
}catch(Exceptione){
e.printStackTrace();
}
try{
socket.close();
}catch(Exceptione){
e.printStackTrace();
}
}
protectedvoidsendFile(BufferedOutputStreambos,PrintWriterpw,
Stringfilename)throwsException{
try{
java.io.BufferedInputStreambis=newjava.io.BufferedInputStream(
newFileInputStream(filename));
byte[]data=newbyte[10*1024];
intread=bis.read(data);
pw.println("HTTP/1.0200Okay");
pw.println();
pw.flush();
bos.flush();
while(read!=-1){
bos.write(data,0,read);
read=bis.read(data);
}
bos.flush();
}catch(Exceptione){
pw.flush();
bos.flush();
}
}
protectedvoidsendDir(BufferedOutputStreambos,PrintWriterpw,
Filedir,Stringreq)throwsException{
try{
pw.println("HTTP/1.0200Okay");
pw.println();
pw.flush();
pw.print("Directoryof");
pw.print(req);
pw.print(" Directoryof");
pw.print(req);
pw.println("
");
File[]contents=dir.listFiles();
for(inti=0;i");
pw.print("");
if(contents[i].isDirectory())
pw.print("Dir->");
pw.print(contents[i].getName());
pw.print(" ");
pw.println("");
}
pw.println("");
pw.flush();
}catch(Exceptione){
pw.flush();
bos.flush();
}
}
}
//Checkthatafilepathhasbeenspecifiedandaportnumber
protectedvoidparseParams(String[]args)throwsException{
switch(args.length){
case1:
case0:
System.err.println("Syntax:"+this.getClass().getName()
+"docrootport");
System.exit(0);
default:
this.docroot=args[0];
this.port=Integer.parseInt(args[1]);
break;
}
}
publicWebServerDemo(String[]args)throwsException{
System.out.println("Checkingforparamters");
//Checkforcommandlineparameters
parseParams(args);
System.out.print("Startingwebserver......");
//Createanewserversocket
this.ss=newServerSocket(this.port);
System.out.println("OK");
for(;;){
//Acceptanewsocketconnectionfromourserversocket
Socketaccept=ss.accept();
//Startanewhandlerinstancetoprocesstherequest
newHandler(accept,docroot).start();
}
}
//Startaninstanceofthewebserverrunning
publicstaticvoidmain(String[]args)throwsException{
WebServerDemowebServerDemo=newWebServerDemo(args);
}
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!