首页 > 代码库 > HTTP1.0工作原理
HTTP1.0工作原理
1.HTTP工作原理
《HTTP响应报文与工作原理详解》讲的比较详细了。
2.示例
(1)server端程序如下:
1 package org.yeyouluo.demo.jsp; 2 3 import java.io.BufferedReader; 4 import java.io.BufferedWriter; 5 import java.io.IOException; 6 import java.io.InputStreamReader; 7 import java.io.OutputStreamWriter; 8 import java.io.PrintWriter; 9 import java.net.ServerSocket;10 import java.net.Socket;11 import java.util.concurrent.ExecutorService;12 import java.util.concurrent.Executors;13 14 /**15 * 实现HTTP 1.0的服务器,对于所有的HTTP请求,会把HTTP请求头响应回去。16 * @author yeyouluo17 *18 */19 public class MyHTTPServer {20 21 public static void main(String[] args) throws IOException {22 int port = 80;23 ServerSocket serverSocket = new ServerSocket(port); 24 System.out.println("启动服务,绑定端口: " + port);25 26 ExecutorService fixedThreadPool = Executors.newFixedThreadPool(30); //5.线程池27 28 //6.这个循环不停监听socket连接,使用SocketHandler处理连入的socket,而这个处理是放在线程池中的。29 while(true){ 30 Socket clientSocket = serverSocket.accept();31 System.out.println("新的连接"+clientSocket.getInetAddress() + ":" + clientSocket.getPort());32 try{33 fixedThreadPool.execute(new SocketHandler(clientSocket));34 }catch(Exception e){35 e.printStackTrace();36 }37 }38 }39 40 }41 42 class SocketHandler implements Runnable{43 static final String CRLF = "\r\n"; //1.换行符44 private Socket clientSocket;45 46 public SocketHandler(Socket clientSocket) {47 super();48 this.clientSocket = clientSocket;49 }50 51 public void handleSocket(Socket clientSocket) throws IOException{52 BufferedReader in = new BufferedReader(53 new InputStreamReader(clientSocket.getInputStream())54 );55 56 PrintWriter out = new PrintWriter(57 new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()))58 ,true);59 60 String requestHeader = "";61 String s;62 while( (s = in.readLine()) != null ){63 s += CRLF; //2.很重要,默认情况下in.readLine的结果中‘\r\n‘被去掉了64 requestHeader += s;65 if( CRLF.equals(s) ){ //如果读取的一行数据只有换行符,说明请求头已经结束了66 break;67 }68 }69 70 System.out.println("客户端请求头:\n" + requestHeader);71 72 String responseBody = "客户端的请求头是:\n"+requestHeader;73 String responseHeader = "HTTP/1.0 200 OK\r\n" +74 "Content-Type: text/plain; charset=UTF-8\r\n" +75 "Content-Length: "+responseBody.getBytes().length+"\r\n" +76 "\r\n";77 System.out.println("响应头:\n" + responseHeader);78 79 out.write(responseHeader);80 out.write(responseBody);81 out.flush();82 83 out.close();84 in.close();85 clientSocket.close();86 }87 88 @Override89 public void run() {90 try {91 handleSocket(clientSocket);92 } catch (IOException e) {93 // TODO Auto-generated catch block94 e.printStackTrace();95 }96 }97 98 }
启动server端。
(2)client端直接通过浏览器或curl工具发送http请求即可。比如在浏览器中输入http://127.0.0.1 。
(3)server端控制台打印如下:
3.参考
http://wiki.jikexueyuan.com/project/java-web/00-02.html
HTTP1.0工作原理
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。