http是应用层的一种协议,我们浏览器就是基于http协议,写个例子以后供参考。
package com.tomcat.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestMain {
private static ServerSocket serverSocket;
private static ExecutorService executorService;
private final static int POOL_SIZE = 100;
//以下是一个http请求响应的小例子,tomcat就是在此基础上进行的,只不过tomcat进一步解析了web.xml
public static void main(String[] args) throws UnsupportedEncodingException, IOException {
serverSocket = new ServerSocket(8089);
executorService = Executors.newFixedThreadPool(POOL_SIZE);
executorService.execute(new Runnable() {
@Override
public void run() {
Socket socket = null;
while (true) {
try {
socket = serverSocket.accept();
//socket的输入流其实就是请求的信息
//这里会有个比较奇葩的问题,就是如果不把socket的InputStream从内存中read出来,谷歌浏览器会出现问题
//因为每次谷歌浏览器请求会多发一次请求获取favicon.ico,如自动发送http://127.0.0.1:8089/favicon.ico
//这个请求就是请求浏览器地址栏最左边的小图标
//如果不read出来会出现阻塞现象,导致favicon.ico请求写不进内存,从而刷新页面有时会出错,无法响应请求
//火狐和IE暂时没有发现这个奇葩问题
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
StringBuffer httpReqStr = new StringBuffer("");
int rlength;
char[] chars = new char[100];
rlength = reader.read(chars);
while(rlength == 100){
httpReqStr.append(chars);
chars = new char[100];
rlength = reader.read(chars);
}
httpReqStr.append(chars);
System.out.println(httpReqStr);//获取请求(包括请求信息以及请求头)
} catch (IOException e) {
e.printStackTrace();
}
PrintWriter writer;
try {
writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
writer.println("HTTP/1.1 200 OK");//响应状态行
writer.println("Content-Type: text/html;charset=UTF-8");//响应格式行
writer.println("");//空行
//下面响应体
writer.println("<!DOCTYPE html>");
writer.println("<html>");
writer.println("Welcome to my HttpTest!!");
writer.println("</html>");
writer.flush();
writer.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//其实wirter关了,socket也关了
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
}
启动后相当于一个小小的服务器,下面为结果截图:
1.控制台获取的请求信息
2.谷歌浏览器的结果