java实现一个简单的实现一个简单的Web服务器实例解析服务器实例解析
主要介绍了java实现一个简单的Web服务器实例解析,分享了相关代码示例,小编觉得还是挺不错的,具有一定
借鉴价值,需要的朋友可以参考下
Web服务器也称为超文本传输协议服务器,使用http与其客户端进行通信,基于java的web服务器会使用两个重要的类,
java.net.Socket类和java.net.ServerSocket类,并基于发送http消息进行通信。
这个简单的Web服务器会有以下三个类:
*HttpServer
*Request
*Response
应用程序的入口在HttpServer类中,main()方法创建一个HttpServer实例,然后调用其await()方法,顾名思义,await()方法会在
指定端口上等待HTTP请求,对其进行处理,然后发送响应信息回客户端,在接收到关闭命令前,它会保持等待状态。
该应用程序仅发送位于指定目录的静态资源的请求,如html文件和图像,它也可以将传入到的http请求字节流显示到控制台,
但是,它并不发送任何头信息到浏览器,如日期或者cookies等。
下面为这几个类的源码下面为这几个类的源码
Request::
package cn.com.server;
import java.io.InputStream;
public class Request {
private InputStream input;
private String uri;
public Request(InputStream input){
this.input=input;
}
public void parse(){
//Read a set of characters from the socket
StringBuffer request=new StringBuffer(2048);
int i;
byte[] buffer=new byte[2048];
try {
i=input.read(buffer);
}
catch (Exception e) {
e.printStackTrace();
i=-1;
}
for (int j=0;j<i;j++){
request.append((char)buffer[j]);
}
System.out.print(request.toString());
uri=parseUri(request.toString());
}
public String parseUri(String requestString){
int index1,index2;
index1=requestString.indexOf(" ");
if(index1!=-1){
index2=requestString.indexOf(" ",index1+1);
if(index2>index1){
return requestString.substring(index1+1,index2);
}
}
return null;
}
public String getUri(){
return this.uri;
}
}
Request类表示一个HTTP请求,可以传递InputStream对象来创建Request对象,可以调用InputStream对象中的read()方法来
读取HTTP请求的原始数据。
上述源码中的parse()方法用于解析Http请求的原始数据,parse()方法会调用私有方法parseUrI()来解析HTTP请求的URI,除此之
外,并没有做太多的工作,parseUri()方法将URI存储在变量uri中,调用公共方法getUri()会返回请求的uri。
Response:
package cn.com.server;