72 手写HTTP服务器

HTTP服务器

http协议的底层是tcp/ip协议,浏览器与服务器的交互就是tcp的通信过程。所以我们可以使用先前学的tcp通讯知识点搭建一个简单的服务器。

思路

  • 使用ServerSocket创建一个服务器端(指定端口为8888),阻塞式接受tcp请求(accept()方法)
  • 从浏览器访问:http://localhost:8888 就能与服务器端建立连接
  • 建立了连接相当于tcp连接建立完成,可以使用Socket client = x.accept() 创建浏览器端的socket
  • 创建输入流获取浏览器传入的信息(请求信息)
  • 创建输出流返回响应信息,响应信息格式是固定的,一旦写错,浏览器无法接收响应信息
  • 归纳如下:
    public static void main(String[] args) {
    	//创建服务器
    	//阻塞式接受
    	//创建输入流
    	//读取请求
    	//创建输出流
    	//返回响应
    		//响应头
    		//响应内容
    }
    

      

代码

必读注意事项,响应头必须不能写错:

  • HTTP/1.1 200 OK 缺少此行无法响应,200是状态码,表示响应成功
  • Date:日期
  • Server:服务器名称等信息
  • Content-type:text/html;charset=utf-8  //不写charset=utf-8会导致浏览器解读乱码
  • Content-length:内容长度,注意就是这一行content-length这两个单词绝对不能写错,一旦写错,无法返回响应
  • 这里有回车换行符。缺少此回车换行,同样不能返回响应。
  • 响应数据中不包含响应内容也无法响应
package _20191225_review;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

/**
 * 昨天写的Server真的是云里雾里,今天再来写一次,先面向流程的吧
 * @author TEDU
 *
 */
public class Server {
	public static void main(String[] args) throws IOException {
		//创建服务器
		ServerSocket server = new ServerSocket(8888);
		//阻塞式接受
		Socket client = server.accept();
		//创建输入流
		BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
		//读取请求
		char[] requestInfo = new char[1024*10];
		int len = br.read(requestInfo);
		System.out.println(new String(requestInfo));
		//创建输出流
		OutputStream is = client.getOutputStream();
		//返回响应
			//响应内容
		StringBuilder content = new StringBuilder();
		content.append("<html>");
		content.append("<head>");
		content.append("<title>");
		content.append("响应成功");
		content.append("</title>");
		content.append("</head>");
		content.append("<body>");
		content.append("响应成功了熊");
		content.append("</body>");
		content.append("</html>");
			//响应头:用StringBuilder来存储
		StringBuilder responseInfo = new StringBuilder();
			/*
			 响应行:HTTP/1.1 200 OK
			Date:日期
			Server:服务器名称等信息
			Content-type:text/html
			Content-length:
			 */
		String CRLF = "\r\n";
		int size = content.toString().getBytes().length;
		responseInfo.append("HTTP/1.1 200 OK").append(CRLF);//不添加响应行无法响应!!!!!!!!!!!!!!!!!!
		responseInfo.append("Date:").append(new Date()).append(CRLF);
		responseInfo.append("Server:xiaohei Server/1.0.0").append(CRLF);
		responseInfo.append("Content-type:text/html").append(CRLF);
		responseInfo.append("Content-length:").append(size).append(CRLF);//这一行写错无法响应!!!!!!!!!!!!!!!!
		responseInfo.append(CRLF);//不能缺少的回车换行符!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
			//将content添加进响应消息中
		responseInfo.append(content);//不添加content也无法响应!!!!!!!!!!!!!!!!!!!!!!!!
		is.write(responseInfo.toString().getBytes());
		is.flush();
	}
}

  

 
posted @ 2019-12-25 09:50  Scorpicat  阅读(334)  评论(0编辑  收藏  举报