• A Simple Web Server


    HTTP:Http允许Web服务器和浏览器通过Internet发送并接收数据,是一种基于“请求 - 响应”的协议。

    一、HTTP 请求

    • 请求方法  - URI - 协议/版本
    • 请求头
    • 实体

    二、HTTP 响应

    • 协议 - 状态码 - 描述
    • 响应头
    • 响应实体段
     1 package org.http;
    2
    3 import java.io.File;
    4 import java.io.IOException;
    5 import java.io.InputStream;
    6 import java.io.OutputStream;
    7 import java.net.ServerSocket;
    8 import java.net.Socket;
    9
    10 public class HttpServer
    11 {
    12 public static final String WEB_ROOT = System.getProperty("user.dir")
    13 + File.separator + "WebContent";
    14
    15 private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
    16
    17 private final int PORT = 8080;
    18
    19 private boolean shutdown = false;
    20
    21 public static void main(String[] args)
    22 {
    23 HttpServer server = new HttpServer();
    24 server.await();
    25 }
    26
    27 public void await()
    28 {
    29 ServerSocket serverSocket = null;
    30 try
    31 {
    32 serverSocket = new ServerSocket(PORT);
    33 }
    34 catch (IOException e)
    35 {
    36 e.printStackTrace();
    37 System.exit(1);
    38 }
    39 // Loop waitting for a request
    40 while (!shutdown)
    41 {
    42 Socket socket = null;
    43 InputStream input = null;
    44 OutputStream output = null;
    45 try
    46 {
    47 socket = serverSocket.accept();
    48 input = socket.getInputStream();
    49 output = socket.getOutputStream();
    50
    51 // create request object and parse
    52 Request request = new Request(input);
    53 request.parse();
    54
    55 // create response object
    56 Response response = new Response(output);
    57 response.setRequest(request);
    58 response.sendStaticResource();
    59 shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
    60 }
    61 catch (IOException e)
    62 {
    63 e.printStackTrace();
    64 }
    65 finally
    66 {
    67 try
    68 {
    69 socket.close();
    70 }
    71 catch (IOException e)
    72 {
    73 e.printStackTrace();
    74 }
    75 }
    76
    77 }
    78 }
    79 }
     1 package org.http;
    2
    3 import java.io.IOException;
    4 import java.io.InputStream;
    5
    6 public class Request
    7 {
    8 private InputStream input;
    9 private String uri;
    10
    11 public Request(InputStream input)
    12 {
    13 this.input = input;
    14 }
    15
    16 public void parse()
    17 {
    18 StringBuffer request = new StringBuffer(2048);
    19 int i;
    20 byte[] buffer = new byte[2048];
    21 try
    22 {
    23 i = input.read(buffer);
    24 }
    25 catch (IOException e)
    26 {
    27 e.printStackTrace();
    28 i = -1;
    29 }
    30 for (int j = 0; j < i; j++)
    31 {
    32 request.append((char) buffer[j]);
    33 }
    34 System.out.println(request.toString());
    35 uri = parseUri(request.toString());
    36 }
    37
    38 private String parseUri(String requestStr)
    39 {
    40 int index1, index2;
    41 index1 = requestStr.indexOf(' ');
    42 if (index1 != -1)
    43 {
    44 index2 = requestStr.indexOf(' ', index1 + 1);
    45 if (index2 > index1)
    46 {
    47 return requestStr.substring(index1 + 1, index2);
    48 }
    49 }
    50 return "";
    51 }
    52
    53 public String getUri()
    54 {
    55 return uri;
    56 }
    57 }
     1 package org.http;
    2
    3 import java.io.File;
    4 import java.io.FileInputStream;
    5 import java.io.IOException;
    6 import java.io.OutputStream;
    7
    8 public class Response
    9 {
    10 private static final int BUFFER_SIZE = 1024;
    11 private Request request;
    12 private OutputStream output;
    13
    14 public Response(OutputStream output)
    15 {
    16 this.output = output;
    17 }
    18
    19 public void sendStaticResource()
    20 {
    21 byte[] bytes = new byte[BUFFER_SIZE];
    22 FileInputStream fis = null;
    23 try
    24 {
    25 File file = new File(HttpServer.WEB_ROOT, request.getUri());
    26
    27 if (file.exists())
    28 {
    29 fis = new FileInputStream(file);
    30 int ch = fis.read(bytes, 0, BUFFER_SIZE);
    31 while (ch != -1)
    32 {
    33 output.write(bytes, 0, ch);
    34 ch = fis.read(bytes, 0, BUFFER_SIZE);
    35 }
    36 }
    37 else
    38 {
    39 String errorMessage = "HTTP/1.1 404 File Not Found\r\n"
    40 + "Content-Type : text/html\r\n" + "\r\n"
    41 + "<h1>File Not Found</h1>";
    42 output.write(errorMessage.getBytes());
    43 }
    44 }
    45 catch (Exception e)
    46 {
    47 e.printStackTrace();
    48 }
    49 finally
    50 {
    51 if (fis != null)
    52 try
    53 {
    54 fis.close();
    55 }
    56 catch (IOException e)
    57 {
    58 e.printStackTrace();
    59 }
    60 }
    61
    62 }
    63
    64 public void setRequest(Request request)
    65 {
    66 this.request = request;
    67 }
    68 }


    打印HTTP响应: 

     1 package org.http;
    2
    3 import java.io.BufferedReader;
    4 import java.io.IOException;
    5 import java.io.InputStream;
    6 import java.io.InputStreamReader;
    7 import java.io.OutputStream;
    8 import java.io.PrintWriter;
    9 import java.net.Socket;
    10 import java.net.UnknownHostException;
    11
    12 public class Client
    13 {
    14 public static void main(String[] args) throws Exception
    15 {
    16 Socket socket = new Socket("127.0.0.1", 8080);
    17 OutputStream os = socket.getOutputStream();
    18 InputStream is = socket.getInputStream();
    19 boolean autoFlush = true;
    20 PrintWriter out = new PrintWriter(os, autoFlush);
    21 BufferedReader in = new BufferedReader(new InputStreamReader(is));
    22 out.println("Get /index.jsp HTTP/1.1");
    23 out.println("Host: localhost:8080");
    24 out.println("Connection: close");
    25 out.println();
    26
    27 boolean loop = true;
    28 StringBuffer sb = new StringBuffer(8096);
    29 while (loop)
    30 {
    31 if (in.ready())
    32 {
    33 int i = 0;
    34 do
    35 {
    36 i = in.read();
    37 sb.append((char) i);
    38 }
    39 while (i != -1);
    40 loop = false;
    41 }
    42 Thread.sleep(1000);
    43 }
    44 System.out.println(sb.toString());
    45 socket.close();
    46 }
    47 }
  • 相关阅读:
    学习H5一周随笔
    vue项目中vux的使用
    git操作常用命令
    vue2.0 实现全选和全不选
    鼠标事件以及clientX、offsetX、screenX、pageX、x的区别
    js编写当天简单日历
    UIView.frame的骗局
    设计模式笔记感悟
    实用图像处理入门
    实用图像处理入门
  • 原文地址:https://www.cnblogs.com/xuekyo/p/2424383.html
Copyright © 2020-2023  润新知