1.一个简单的web容器其实就是一个简单的socket类的服务端,然后通过浏览器访问,将请求的内容输出到页面。
2.示例:HttpServer.java
package com.diytomcat.http;
import java.net.Socket;
import java.net.UnknownHostException;
import java.net.ServerSocket;
import java.net.InetAddress;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
public class HttpServer {
public static final String WEB_ROOT =
System.getProperty("user.dir") + File.separator + "WebContent";
private final int port = 8080;
public void accept() throws UnknownHostException, IOException{
ServerSocket serverSocket = new ServerSocket(port, 2, InetAddress.getByName("127.0.0.1"));
while(true){
Socket socket = serverSocket.accept();
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
PrintWriter writer = new PrintWriter(out);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
byte[] bytes = new byte[1024];
FileInputStream fis = null;
try {
File file = new File(HttpServer.WEB_ROOT, "/test.jsp");
if (file.exists()) {
fis = new FileInputStream(file);
int ch = fis.read(bytes, 0, 1024);
while (ch!=-1) {
out.write(bytes, 0, ch);
ch = fis.read(bytes, 0, 1024);
}
}
else {
// file not found
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>";
out.write(errorMessage.getBytes());
}
}
catch (Exception e) {
// thrown if cannot instantiate a File object
System.out.println(e.toString() );
}
finally {
if (fis!=null)
fis.close();
}
socket.close();
}
}
public void sendStaticResource() throws IOException {
}
public static void main(String[] args){
HttpServer server = new HttpServer();
try {
server.accept();
} catch (IOException e) {
e.printStackTrace();
}
}
}