通过前一章的学习,我们基本了解了Http协议,本章将通过具体实例来演示一下Http的交互,在这之前,有必要了解一下Socket.套接字是网络连接的一个端点。要通过互联网进行通信,至少需要一对套接字一个运行于客户端,另一个运行于服务器端.在java中分别用java.net.Socket和java.net.ServerSokcet来创建
客户端socket可以通过
public Socket(java.lang.String host,int port)
来创建,一旦成功创建了一个Socket类的实例,我们就可以使用它来发送和接受字节流.ServerSocket和Socket不同,它是用来等待客户端的连接请求。一旦服务器套接字获得一个连接请求,它将创建一个Socket实例来与客户端进行通信。服务端ServerSocket可以通过
public ServerSokcet(int port,int backLog,InetAddress bindingAddress)
来创建,一旦成功创建了ServerSocket实例,那么它就在所绑定地址的端口等待传入的连接请求,我们可以通过调用ServerSocket类的accept方法做到这点,这个方法只会在有连接请求时才会返回,并且返回一个Socket类的实例.
了解了上面的基础知识后,我们开始用Socket来实现Http交互过程
public class Request {
private InputStream input;
private String uri;
public InputStream getInput() {
return input;
}
public void setInput(InputStream input) {
this.input = input;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public Request(InputStream input) {
this.input = input;
}
public void parse(){
StringBuffer request=new StringBuffer(2048);
int i;
byte[]buffer=new byte[2048];
try{
i=input.read(buffer);
}catch(IOException e){
e.printStackTrace();
i=-1;
}
for(int j=0;j<i;j++){
request.append((char)buffer[j]);
}
System.out.println(request.toString());
uri=parseUri(request.toString());
}
private 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 class Response {
private Request request;
private OutputStream output;
private static final int BUFFER_SIZE = 1024;
public Request getRequest() {
return request;
}
public void setRequest(Request request) {
this.request = request;
}
public OutputStream getOutput() {
return output;
}
public void setOutput(OutputStream output) {
this.output = output;
}
public Response(OutputStream output) {
this.output = output;
}
public void sendStaticResource() throws IOException {
byte[] bytes = new byte[BUFFER_SIZE];
FileInputStream fis = null;
try {
File file = new File(HttpServer.WEB_ROOT, request.getUri());
if (file.exists()) {
fis = new FileInputStream(file);
int ch = fis.read(bytes, 0, BUFFER_SIZE);
while (ch != -1) {
output.write(bytes, 0, ch);
ch = fis.read(bytes, 0, BUFFER_SIZE);
}
} else {
String errorMessage = "HTTP/1.1 404 File Not Found\r\n"
+ "Content-Type:text/html\r\n"
+ "Content-Length:23\r\n" + "\r\n"
+ "<h1>File Not Found</h1>";
output.write(errorMessage.getBytes());
}
} catch (Exception e) {
}finally{
if(fis!=null)
fis.close();
}
}
}
public class HttpServer {
private boolean shutdown=false;
private static final String SHUTDOWN_COMMAND="/SHUTDOWN";
public static final String WEB_ROOT=System.getProperty("user.dir")+File.separator+"webroot";
/**
* @param args
*/
public static void main(String[] args) {
HttpServer server=new HttpServer();
server.await();
}
public void await(){
ServerSocket serverSokcet=null;
int port=8080;
try {
serverSokcet=new ServerSocket(port,1,InetAddress.getByName("127.0.0.1"));
} catch (Exception e) {
System.exit(1);
}
while(!shutdown){
Socket socket=null;
InputStream input=null;
OutputStream output=null;
try {
socket=serverSokcet.accept();
input=socket.getInputStream();
output=socket.getOutputStream();
Request request=new Request(input);
request.parse();
Response response=new Response(output);
response.setRequest(request);
response.sendStaticResource();
socket.close();
shutdown=request.getUri().equals(SHUTDOWN_COMMAND);
} catch (IOException e) {
e.printStackTrace();
continue;
}
}
}
}
request类根据http协议解析出客户端的请求URL,response根据请求的url去找相应的文件,如果找到就读取该文件,并返回给客户端,如果没有找到就返回404页面,HttpServer则是一直监听是否有客户端连接