做为后端开发人员,在实际的工做中咱们会很是高频地使用到web服务器。而tomcat做为web服务器领域中举足轻重的一个web框架,又是不能不学习和了解的。html
tomcat实际上是一个web框架,那么其内部是怎么实现的呢?若是不用tomcat咱们能本身实现一个web服务器吗?java
首先,tomcat内部的实现是很是复杂的,也有很是多的各种组件,咱们在后续章节会深刻地了解。
其次,本章咱们将本身实现一个web服务器的。web
下面咱们就本身来实现一个看看。(【注】:参考了《How tomcat works》这本书)后端
http是一种协议(超文本传输协议),容许web服务器和浏览器经过Internet来发送和接受数据,是一种请求/响应协议。http底层使用TCP来进行通讯。目前,http已经迭代到了2.x版本,从最初的0.九、1.0、1.1到如今的2.x,每一个迭代都加了不少功能。浏览器
在http中,始终都是客户端发起一个请求,服务器接受到请求以后,而后处理逻辑,处理完成以后再发送响应数据,客户端收到响应数据,而后请求结束。在这个过程当中,客户端和服务器均可以对创建的链接进行中断操做。好比能够经过浏览器的中止按钮。tomcat
一个http协议的请求包含三部分:服务器
举个例子网络
POST /examples/default.jsp HTTP/1.1 Accept: text/plain; text/html Accept-Language: en-gb Connection: Keep-Alive Host: localhost User-Agent: Mozilla/4.0 (compatible; MSIE 4.01; Windows 98) Content-Length: 33 Content-Type: application/x-www-form-urlencoded Accept-Encoding: gzip, deflate lastName=Franks&firstName=Michael
POST
,URI为
/examples/default.jsp
,协议为
HTTP/1.1
,协议版本号为
1.1
。他们之间经过空格来分离。
相似于http协议的请求,响应也包含三个部分。app
举个例子框架
HTTP/1.1 200 OK Server: Microsoft-IIS/4.0 Date: Mon, 5 Jan 2004 13:13:33 GMT Content-Type: text/html Last-Modified: Mon, 5 Jan 2004 13:13:12 GMT Content-Length: 112 <html> <head> <title>HTTP Response Example</title> </head> <body> Welcome to Brainy Software </body> </html>
第一行,HTTP/1.1 200 OK
表示协议、状态和状态描述。
以后表示响应头部。
响应头部和主体内容之间使用空行来分离。
Socket,又叫套接字,是网络链接的一个端点(end point)。套接字容许应用程序从网络中读取和写入数据。两个不一样计算机的不一样进程之间能够经过链接来发送和接受数据。A应用要向B应用发送数据,A应用须要知道B应用所在的IP地址和B应用开放的套接字端口。java里面使用java.net.Socket
来表示一个套接字。
java.net.Socket
最经常使用的一个构造方法为:public Socket(String host, int port);
,host表示主机名或ip地址,port表示套接字端口。咱们来看一个例子:
Socket socket = new Socket("127.0.0.1", "8080"); OutputStream os = socket.getOutputStream(); boolean autoflush = true; PrintWriter out = new PrintWriter( socket.getOutputStream(), autoflush); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputstream())); // send an HTTP request to the web server out.println("GET /index.jsp HTTP/1.1"); out.println("Host: localhost:8080"); out.println("Connection: Close"); out.println(); // read the response boolean loop = true; StringBuffer sb = new StringBuffer(8096); while (loop) { if (in.ready()) { int i=0; while (i != -1) { i = in.read(); sb.append((char) i); } loop = false; } Thread.currentThread().sleep(50L); }
这儿经过socket.getOutputStream()
来发送数据,使用socket.getInputstream()
来读取数据。
java.net.ServerSocket
来表示一个服务器套接字。
public ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException; new ServerSocket(8080, 1, InetAddress.getByName("127.0.0.1"));
咱们这儿仍是看一个例子。
HttpServer表示一个服务器端入口,提供了一个main方法,并一直在8080端口等待,直到客户端创建一个链接。这时,服务器经过生成一个Socket来对此链接进行处理。
public class HttpServer { /** WEB_ROOT is the directory where our HTML and other files reside. * For this package, WEB_ROOT is the "webroot" directory under the working * directory. * The working directory is the location in the file system * from where the java command was invoked. */ public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "webroot"; // shutdown command private static final String SHUTDOWN_COMMAND = "/SHUTDOWN"; // the shutdown command received private boolean shutdown = false; public static void main(String[] args) { HttpServer server = new HttpServer(); server.await(); } public void await() { ServerSocket serverSocket = null; int port = 8080; try { serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1")); } catch (IOException e) { e.printStackTrace(); System.exit(1); } // Loop waiting for a request while (!shutdown) { Socket socket = null; InputStream input = null; OutputStream output = null; try { socket = serverSocket.accept(); input = socket.getInputStream(); output = socket.getOutputStream(); // create Request object and parse Request request = new Request(input); request.parse(); // create Response object Response response = new Response(output); response.setRequest(request); response.sendStaticResource(); // Close the socket socket.close(); //check if the previous URI is a shutdown command shutdown = request.getUri().equals(SHUTDOWN_COMMAND); } catch (Exception e) { e.printStackTrace(); continue; } } } }
Request对象主要完成几件事情
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 (IOException 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()); } 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 String getUri() { return uri; } }
Response主要是向客户端发送文件内容(若是请求的uri指向的文件存在)。
public class Response { private static final int BUFFER_SIZE = 1024; Request request; OutputStream output; public Response(OutputStream output) { this.output = output; } 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); while (ch!=-1) { output.write(bytes, 0, ch); ch = fis.read(bytes, 0, BUFFER_SIZE); } } 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>"; output.write(errorMessage.getBytes()); } } catch (Exception e) { // thrown if cannot instantiate a File object System.out.println(e.toString() ); } finally { if (fis!=null) fis.close(); } } }
在看了上面的例子以后,咱们惊奇地发现,在Java里面实现一个web服务器真容易,代码也很是简单和清晰!
既然咱们能很简单地实现web服务器,为啥咱们还须要tomcat呢?它又给咱们带来了哪些组件和特性呢,它又是怎么组装这些组件的呢,后续章节咱们将逐层分析。
这是咱们后面将要分析的内容,让咱们拭目以待!