簡(jiǎn)單的Web服務(wù)器
使用三個(gè)類 HttpServer用來創(chuàng)建ServerSocket铡羡,Response用來接收Request和向客戶端返回信息汛聚,Request處理客戶端傳來的信息
HttpServer.java
package com.ly2;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class HttpServer {
public static final String WEB_ROOT=
System.getProperty("user.dir")+ File.separator
+"webroot";
private static final String SHUTDOWN_COMMAND="/SHUTDOWN";
private boolean shutdown=false;
public static void main(String[] args) {
System.out.println(WEB_ROOT);
HttpServer server=new HttpServer();
server.await();
}
private void await() {
int port=8080;
try(ServerSocket serverSocket =new ServerSocket
(port,1, InetAddress.getByName("127.0.0.1"))){
while (!shutdown){
try(Socket socket=serverSocket.accept()) {
InputStream inputStream=socket.getInputStream();
OutputStream outputStream=socket.getOutputStream();
//處理輸入
Request request=new Request(inputStream);
//解析HTTP請(qǐng)求的原始數(shù)據(jù)
request.parse();
Response response=new Response(outputStream);
response.setRequest(request);
response.sendStaticResource();
shutdown=request.getUri().equals(SHUTDOWN_COMMAND);
}catch (Exception e){
e.printStackTrace();
}
}
}catch (Exception e){
e.printStackTrace();
System.exit(1);
}
}
}
Request.java
package com.ly2;
import java.io.IOException;
import java.io.InputStream;
public class Request {
private InputStream input;
private String uri;
public Request(InputStream inputStream) {
this.input=inputStream;
}
public void parse() {
StringBuffer request=new StringBuffer(2048);
int i;
byte[] buffer=new byte[2048];
try{
//這里返回讀取的實(shí)際字節(jié)的大小
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());
}
/**
* 獲取uri
* @param requestString
* @return
*/
private String parseUri(String requestString){
int index1,index2;
index1=requestString.indexOf(' ');
if(index1 != -1){
index2=requestString.indexOf(' ',index1+1);
if(index2 > index1){
//截取http請(qǐng)求的rui
return requestString.substring(index1+1,index2);
}
}
return null;
}
public String getUri() {
return uri;
}
}
Response.java
package com.ly2;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
public class Response {
private static final int BUFFER_SIZE=1024;
Request request;
OutputStream output;
public Response(OutputStream outputStream) {
this.output=outputStream;
}
public void setRequest(Request request) {
this.request=request;
}
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);
//注意 這里一定要添加響應(yīng)返回頭信息,否則chrome不無打開,
//會(huì)出現(xiàn)ERR_INVALID_HTTP_RESPONSE
String head="HTTP/1.1 200 OK\r\n"+
"Content-Type: text/html\r\n\r\n";
output.write(head.getBytes());
while (ch!=-1){
output.write(bytes,0,ch);
//一次性讀取部分字節(jié)
ch=fis.read(bytes,0,BUFFER_SIZE);
}
output.flush();
}else {
//文件不存在
String errorMessage="HTTP/1.1 404 FileNot 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){
System.out.println(e.toString());
}finally {
if(fis!=null){
fis.close();
}
}
}
}