String filename=getfilename(inline);
File file=new File(filename);
if (file.exists()) { // 若文档存在,则将文档送给Web浏览器
System.out.println(filename " requested.");
outstream.println("HTTP/1.0 200 OK");
outstream.println("MIME_version:1.0");
outstream.println("Content_Type:text/html");
int len=(int)file.length();
outstream.println("Content_Length:" len);
outstream.println("");
sendfile(outstream,file); // 发送文档
outstream.flush();
} else { // 文档不存在时
String notfound="<html><head><title>Not Found</title></head>
<body><h1>Error 404-file not found</h1></body></html>";
outstream.println("HTTP/1.0 404 no found");
outstream.println("Content_Type:text/html");
outstream.println("Content_Length:" notfound.length() 2);
outstream.println("");
outstream.println(notfound);
outstream.flush();
}
}
long m1=1;
while (m1<11100000) {m1 ;} // 延时
client.close();
} catch (IOException e) {
System.out.println("Exception:" e);
}
}
/* 获取请求类型是否为“GET” */
boolean getrequest(String s) {
if (s.length()>0)
{
if (s.substring(0,3).equalsIgnoreCase("GET")) return true;
}
return false;
}
/* 获取要访问的文档名 */
String getfilename(String s) {
String f=s.substring(s.indexOf(' ') 1);
f=f.substring(0,f.indexOf(' '));
try {
if (f.charAt(0)=='/')
f=f.substring(1);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("Exception:" e);
}
if (f.equals("")) f="index.html";
return f;
}
/*把指定文档发送给Web浏览器 */
void sendfile(PrintStream outs,File file) {
try {
DataInputStream in=new DataInputStream(new FileInputStream(file));
int len=(int)file.length();
byte buf[]=new byte[len];
in.readFully(buf);
outs.write(buf,0,len);
outs.flush();
in.close();
} catch (Exception e) {
System.out.println("Error retrieving file.");
System.exit(1);
}
}
}
程式中的ConnectionThread线程子类用来分析一个Web浏览器提交的请求,并将应答信息传回给Web浏览器。其中,getrequest()方法用来检测客户的请求是否为“GET”;getfilename(s)方法是从客户请求信息s中获取要访问的HTML文档名;sendfile()方法把指定文档内容通过socket传回给Web浏览器。
对上述程式的getrequest()方法和相关部分作修改,也能对POST请求进行处理。
三、运行实例
为了测试上述程式的正确性,将编译后的WebServer.class、ConnectionThread.class和下面的index.html文档置于网络的某台主机的同一目录中(如:主机NT40SRV的C:\JWEB目录)。
程式2:index.html文档
<HTML>
<HEAD>
<META HTTP-EQUIV="Content-Type" content="text/html; charset=gb_2312-80">
<TITLE>Java Web服务器</TITLE>
</HEAD>
<BODY>
<h3>这是用JAVA写出的WEB服务器主页</h3>
1998年8月28日
<hr>
</BODY>
</HTML>
首先在该主机上用java命令运行WebServer.class:
C:\jweb>java webserver
然后在客户机运行浏览器软件,在URL处输入WebServer程式所属的URL地址(如:http://nt40srv:8080/index.html),就在浏览器窗口显示出指定的HTML文档。
注意,不能缺省端口号8080,如缺省,则运行该主机的正常WEB服务器。
说明,不具备网络条件的可在安装了Windows 95的单机上进行测试,方法是用localhost或127.0.0.1代替URL地址的域名部分,即URL地址为http://localhost:8080。
文章整理:西部数码--专业提供域名注册、虚拟主机服务
http://www.west263.com
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!




