HowTomcatWorks00

Socket連接

Server

public class HttpServer {

  /** WEB_ROOT is the directory where our HTML and other files reside.
   *  For this package, WEB_ROOT is the "webroot" directory under the working
   *  directory.
   *  The working directory is the location in the file system
   *  from where the java command was invoked.
   */
  public static final String WEB_ROOT =
    System.getProperty("user.dir") + File.separator  + "webroot";

  // shutdown command
  private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";

  // the shutdown command received
  private boolean shutdown = false;

  public static void main(String[] args) {
    HttpServer server = new HttpServer();
    server.await();
  }

  public void await() {
    ServerSocket serverSocket = null;
    int port = 8080;
    try {
      serverSocket =  new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
    }
    catch (IOException e) {
      e.printStackTrace();
      System.exit(1);
    }

    // Loop waiting for a request
    while (!shutdown) {
      Socket socket = null;
      InputStream input = null;
      OutputStream output = null;
      try {
        socket = serverSocket.accept();
        input = socket.getInputStream();
        output = socket.getOutputStream();

        // create Request object and parse
        Request request = new Request(input);
        request.parse();

        // create Response object
        Response response = new Response(output);
        response.setRequest(request);
        response.sendStaticResource();

        // Close the socket
        socket.close();

        //check if the previous URI is a shutdown command
        shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
      }
      catch (Exception e) {
        e.printStackTrace();
        continue;
      }
    }
  }
}

Server的關鍵是accept方法月弛,它只有在接收到一個請求時才返回一個socket钉答,然后借此socket來生成input和output流

Request

public class Request {

  private InputStream input;
  private String uri;

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

  public void parse() {
    // Read a set of characters from the socket
    StringBuffer request = new StringBuffer(2048);
    int i;
    byte[] buffer = new byte[2048];
    try {
      i = input.read(buffer);
    }
    catch (IOException e) {
      e.printStackTrace();
      i = -1;
    }
    for (int j=0; j<i; j++) {
      request.append((char) buffer[j]);
    }
    System.out.print(request.toString());
    uri = parseUri(request.toString());
  }

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

}

Request來解析Uri,parseUri()方法通過提取請求頭第一行兩個空格間來獲得uri

Response

public class Response {

  private static final int BUFFER_SIZE = 1024;
  Request request;
  OutputStream output;

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

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

  public void sendStaticResource() throws IOException {
    byte[] bytes = new byte[BUFFER_SIZE];
    FileInputStream fis = null;
    try {
      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) {
          output.write(bytes, 0, ch);
          ch = fis.read(bytes, 0, BUFFER_SIZE);
        }
      }
      else {
        // file not found
        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>";
        output.write(errorMessage.getBytes());
      }
    }
    catch (Exception e) {
      // thrown if cannot instantiate a File object
      System.out.println(e.toString() );
    }
    finally {
      if (fis!=null)
        fis.close();
    }
  }
}

首先利用FIle()構造函數,傳入父子路徑來獲得文件對象匾鸥。如果文件存在則寫入進bytes數組,接著再寫入進output流里面碉纳,利用循環(huán)讀完文件

?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末扫腺,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子村象,更是在濱河造成了極大的恐慌笆环,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,252評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件厚者,死亡現場離奇詭異躁劣,居然都是意外死亡,警方通過查閱死者的電腦和手機库菲,發(fā)現死者居然都...
    沈念sama閱讀 94,886評論 3 399
  • 文/潘曉璐 我一進店門账忘,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人熙宇,你說我怎么就攤上這事鳖擒。” “怎么了烫止?”我有些...
    開封第一講書人閱讀 168,814評論 0 361
  • 文/不壞的土叔 我叫張陵蒋荚,是天一觀的道長。 經常有香客問我馆蠕,道長期升,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,869評論 1 299
  • 正文 為了忘掉前任互躬,我火速辦了婚禮播赁,結果婚禮上,老公的妹妹穿的比我還像新娘吼渡。我一直安慰自己容为,他們只是感情好,可當我...
    茶點故事閱讀 68,888評論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著坎背,像睡著了一般竭缝。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上沼瘫,一...
    開封第一講書人閱讀 52,475評論 1 312
  • 那天抬纸,我揣著相機與錄音,去河邊找鬼耿戚。 笑死湿故,一個胖子當著我的面吹牛,可吹牛的內容都是我干的膜蛔。 我是一名探鬼主播坛猪,決...
    沈念sama閱讀 41,010評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼皂股!你這毒婦竟也來了墅茉?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,924評論 0 277
  • 序言:老撾萬榮一對情侶失蹤呜呐,失蹤者是張志新(化名)和其女友劉穎就斤,沒想到半個月后,有當地人在樹林里發(fā)現了一具尸體蘑辑,經...
    沈念sama閱讀 46,469評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡洋机,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 38,552評論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現自己被綠了洋魂。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片绷旗。...
    茶點故事閱讀 40,680評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖副砍,靈堂內的尸體忽然破棺而出衔肢,到底是詐尸還是另有隱情,我是刑警寧澤豁翎,帶...
    沈念sama閱讀 36,362評論 5 351
  • 正文 年R本政府宣布角骤,位于F島的核電站,受9級特大地震影響谨垃,放射性物質發(fā)生泄漏启搂。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 42,037評論 3 335
  • 文/蒙蒙 一刘陶、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧牢撼,春花似錦匙隔、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,519評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽捍掺。三九已至,卻和暖如春再膳,著一層夾襖步出監(jiān)牢的瞬間挺勿,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,621評論 1 274
  • 我被黑心中介騙來泰國打工喂柒, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留不瓶,地道東北人。 一個月前我還...
    沈念sama閱讀 49,099評論 3 378
  • 正文 我出身青樓灾杰,卻偏偏與公主長得像蚊丐,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子艳吠,可洞房花燭夜當晚...
    茶點故事閱讀 45,691評論 2 361

推薦閱讀更多精彩內容

  • 網絡 理論模型,分為七層物理層數據鏈路層傳輸層會話層表示層應用層 實際應用,分為四層鏈路層網絡層傳輸層應用層 IP...
    FlyingLittlePG閱讀 778評論 0 0
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架麦备,建立于...
    Hsinwong閱讀 22,442評論 1 92
  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現昭娩,斷路器凛篙,智...
    卡卡羅2017閱讀 134,711評論 18 139
  • 推薦指數: 6.0 書籍主旨關鍵詞:特權、焦點栏渺、注意力鞋诗、語言聯想、情景聯想 觀點: 1.統(tǒng)計學現在叫數據分析迈嘹,社會...
    Jenaral閱讀 5,726評論 0 5
  • 城空了秀仲,有樹長出來 我的城死了 鑄起它的人融痛,殺死它的人 不愿因為這件事而驕傲 一座城的終結 永遠因為終結這件事而顯...
    于十六閱讀 2,862評論 6 17