一个简单的Web服务器(一)

一个简单的Web服务器

一.运行机制

一.一个简单的B/S架构包括:

1.      一台Web服务器;

2.      一台客户机;

二.事物交互的过程:

1.  HTTP请求.

2.  HTTP响应

三.HTTP请求:

1.      请求行:

请求方法 统一资源标识符 协议/版本

2.      请求头

3.      实体

实例:

POST  /example/default.jsp  HTTP/1.1

Accept: text/html; text/html

Accept-Language:en-gb

Connection:Keep-Active

Host:localhost

User-Agent:Mozilla/4.0(compatible;MSIE 4.01,Windows98)

Content-length:33

Content-Type:applition/x-www-form-urlencoded

Accept-Encoding:gzip deflate

LastName=Jay&FirstName=King

四.HTTP响应

1.      响应行

协议-状态码-描述

2.      响应头

3.      响应段

实例:

HTTP/1.1  200  OK

Server:Microsoft-IIS/4.0

Date:Mon,5, May 2018 16:09:09 GMT

Last-Modified:Mon,5 May 2018 16:09:02 GMT

Content-Length:112

<html>

<head>

<title>HTTP Response Example</titel>

</head>

<body>

Hello Tomcat!

</body>

</html>

二.实战代码

1.       HttpServer

package JayKing.ASimpleWebServer;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class HttpServer { 
	public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "webroot";
	public static final String SHUTDOWN_COMMAND = "./SHUTDOWN";
	public boolean shutdown = false;
	public static int port = 8080;

	public static void main(String args[]) {
		HttpServer server = new HttpServer();
		server.await();
		
	}
	private void await() {
		ServerSocket serversocket = null;
		try {
			serversocket = new ServerSocket(port,100, InetAddress.getByName("127.0.0.1"));
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.exit(1);
		}
		while (!shutdown) {
			Socket socket = null;
			InputStream in = null;
			OutputStream out = null;
			try {
				socket = serversocket.accept();//服务器没接受一次请求就创建一个socket对象
				in = socket.getInputStream();
				out = socket.getOutputStream();
				Request request = new Request(in);
				request.parse();
				Response response = new Response(out);
				response.setRequest(request);
				response.sendStaticResourse();
				socket.close();
				shutdown = request.getUri().equals("SHUTDOWN_COMMAND");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				continue;
			}

		}

	}
}

2.       Request

package JayKing.ASimpleWebServer;

import java.io.IOException;
import java.io.InputStream;

public class Request {
	private InputStream in;
	private String uri;

	public Request(InputStream in) {
		this.in = in;
	}

	public void parse() {
		StringBuffer request = new StringBuffer(2048);// StringBuffer是变量,可以更改,而String是常量,一旦创建就不可更改.
		int i;
		byte[] buffer = new byte[2048];
		try {
			i = in.read(buffer);// 每次读取2048个字节

		} 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());
	}

	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 uri;
	}

}

3.       Response

package JayKing.ASimpleWebServer;

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 out;

	public Response(OutputStream out) {
		this.out = out;
	}

	public void setRequest(Request request) {
		this.request = request;
	}

	public void sendStaticResourse() throws IOException {
		byte[] bytes = new byte[BUFFER_SIZE];
		FileInputStream fis = null;
		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) {
				out.write(bytes, 0, ch);
				ch = fis.read(bytes, 0, ch);
			}
		} 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>";
			out.write(errorMessage.getBytes());
		}
		fis.close();

	}
}

三.运行应用程序

打开浏览器在地址栏中输入URL:Http://localhost:8080/index.html




猜你喜欢

转载自blog.csdn.net/qq_32951553/article/details/80269635