## 1.簡介
本文是[上一篇文章](http://www.hmoore.net/imnotdown1019/java_core_full/1011421)實踐篇,在上一篇文章中,我分析了選擇器 Selector 的原理。本篇文章,我們來說說 Selector 的應用,如標題所示,這里我基于 Java NIO 實現了一個簡單的 HTTP 服務器。在接下來的章節中,我會詳細講解 HTTP 服務器實現的過程。另外,本文所對應的代碼已經上傳到 GitHub 上了,需要的自取,倉庫地址為[toyhttpd](https://github.com/code4wt/toyhttpd)。好了,廢話不多說,進入正題吧。
## [](http://www.tianxiaobo.com/2018/04/04/%E5%9F%BA%E4%BA%8E-Java-NIO-%E5%AE%9E%E7%8E%B0%E7%AE%80%E5%8D%95%E7%9A%84-HTTP-%E6%9C%8D%E5%8A%A1%E5%99%A8/#2-實現)2\. 實現
本節所介紹的 HTTP 服務器是一個很簡單的實現,僅支持 HTTP 協議極少的特性。包括識別文件后綴,并返回相應的 Content-Type。支持200、400、403、404、500等錯誤碼等。由于支持的特性比較少,所以代碼邏輯也比較簡單,這里羅列一下:
1. 處理請求,解析請求頭
2. 響應請求,從請求頭中獲取資源路徑, 檢測請求的資源路徑是否合法
3. 根據文件后綴匹配 Content-Type
4. 讀取文件數據,并設置 Content-Length,如果文件不存在則返回404
5. 設置響應頭,并將響應頭和數據返回給瀏覽器。
接下來我們按照處理請求和響應請求兩步操作,來說說代碼實現。先來看看核心的代碼結構,如下:
```
/**
* TinyHttpd
*
* @author code4wt
* @date 2018-03-26 22:28:44
*/
public class TinyHttpd {
private static final int DEFAULT_PORT = 8080;
private static final int DEFAULT_BUFFER_SIZE = 4096;
private static final String INDEX_PAGE = "index.html";
private static final String STATIC_RESOURCE_DIR = "static";
private static final String META_RESOURCE_DIR_PREFIX = "/meta/";
private static final String KEY_VALUE_SEPARATOR = ":";
private static final String CRLF = "\r\n";
private int port;
public TinyHttpd() {
this(DEFAULT_PORT);
}
public TinyHttpd(int port) {
this.port = port;
}
public void start() throws IOException {
// 初始化 ServerSocketChannel
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.socket().bind(new InetSocketAddress("localhost", port));
ssc.configureBlocking(false);
// 創建 Selector
Selector selector = Selector.open();
// 注冊事件
ssc.register(selector, SelectionKey.OP_ACCEPT);
while(true) {
int readyNum = selector.select();
if (readyNum == 0) {
continue;
}
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> it = selectedKeys.iterator();
while (it.hasNext()) {
SelectionKey selectionKey = it.next();
it.remove();
if (selectionKey.isAcceptable()) {
SocketChannel socketChannel = ssc.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
} else if (selectionKey.isReadable()) {
// 處理請求
request(selectionKey);
selectionKey.interestOps(SelectionKey.OP_WRITE);
} else if (selectionKey.isWritable()) {
// 響應請求
response(selectionKey);
}
}
}
}
private void request(SelectionKey selectionKey) throws IOException {...}
private Headers parseHeader(String headerStr) {...}
private void response(SelectionKey selectionKey) throws IOException {...}
private void handleOK(SocketChannel channel, String path) throws IOException {...}
private void handleNotFound(SocketChannel channel) {...}
private void handleBadRequest(SocketChannel channel) {...}
private void handleForbidden(SocketChannel channel) {...}
private void handleInternalServerError(SocketChannel channel) {...}
private void handleError(SocketChannel channel, int statusCode) throws IOException {...}
private ByteBuffer readFile(String path) throws IOException {...}
private String getExtension(String path) {...}
private void log(String ip, Headers headers, int code) {}
}
```
上面的代碼是 HTTP 服務器的核心類的代碼結構。其中 request 負責處理請求,response 負責響應請求。handleOK 方法用于響應正常的請求,handleNotFound 等方法用于響應出錯的請求。readFile 方法用于讀取資源文件,getExtension 則是獲取文件后綴。
### [](http://www.tianxiaobo.com/2018/04/04/%E5%9F%BA%E4%BA%8E-Java-NIO-%E5%AE%9E%E7%8E%B0%E7%AE%80%E5%8D%95%E7%9A%84-HTTP-%E6%9C%8D%E5%8A%A1%E5%99%A8/#21-處理請求)2.1 處理請求
處理請求的邏輯比較簡單,主要的工作是解析消息頭。相關代碼如下:
```
private void request(SelectionKey selectionKey) throws IOException {
// 從通道中讀取請求頭數據
SocketChannel channel = (SocketChannel) selectionKey.channel();
ByteBuffer buffer = ByteBuffer.allocate(DEFAULT_BUFFER_SIZE);
channel.read(buffer);
buffer.flip();
byte[] bytes = new byte[buffer.limit()];
buffer.get(bytes);
String headerStr = new String(bytes);
try {
// 解析請求頭
Headers headers = parseHeader(headerStr);
// 將請求頭對象放入 selectionKey 中
selectionKey.attach(Optional.of(headers));
} catch (InvalidHeaderException e) {
selectionKey.attach(Optional.empty());
}
}
private Headers parseHeader(String headerStr) {
if (Objects.isNull(headerStr) || headerStr.isEmpty()) {
throw new InvalidHeaderException();
}
// 解析請求頭第一行
int index = headerStr.indexOf(CRLF);
if (index == -1) {
throw new InvalidHeaderException();
}
Headers headers = new Headers();
String firstLine = headerStr.substring(0, index);
String[] parts = firstLine.split(" ");
/*
* 請求頭的第一行必須由三部分構成,分別為 METHOD PATH VERSION
* 比如:
* GET /index.html HTTP/1.1
*/
if (parts.length < 3) {
throw new InvalidHeaderException();
}
headers.setMethod(parts[0]);
headers.setPath(parts[1]);
headers.setVersion(parts[2]);
// 解析請求頭屬于部分
parts = headerStr.split(CRLF);
for (String part : parts) {
index = part.indexOf(KEY_VALUE_SEPARATOR);
if (index == -1) {
continue;
}
String key = part.substring(0, index);
if (index == -1 || index + 1 >= part.length()) {
headers.set(key, "");
continue;
}
String value = part.substring(index + 1);
headers.set(key, value);
}
return headers;
}
```
簡單總結一下上面的代碼邏輯,首先是從通道中讀取請求頭,然后解析讀取到的請求頭,最后將解析出的 Header 對象放入 selectionKey 中。處理請求的邏輯很簡單,不多說了。
### [](http://www.tianxiaobo.com/2018/04/04/%E5%9F%BA%E4%BA%8E-Java-NIO-%E5%AE%9E%E7%8E%B0%E7%AE%80%E5%8D%95%E7%9A%84-HTTP-%E6%9C%8D%E5%8A%A1%E5%99%A8/#22-響應請求)2.2 響應請求
看完處理請求的邏輯,接下來再來看看響應請求的邏輯。代碼如下:
```
private void response(SelectionKey selectionKey) throws IOException {
SocketChannel channel = (SocketChannel) selectionKey.channel();
// 從 selectionKey 中取出請求頭對象
Optional<Headers> op = (Optional<Headers>) selectionKey.attachment();
// 處理無效請求,返回 400 錯誤
if (!op.isPresent()) {
handleBadRequest(channel);
channel.close();
return;
}
String ip = channel.getRemoteAddress().toString().replace("/", "");
Headers headers = op.get();
// 如果請求 /meta/ 路徑下的資源,則認為是非法請求,返回 403 錯誤
if (headers.getPath().startsWith(META_RESOURCE_DIR_PREFIX)) {
handleForbidden(channel);
channel.close();
log(ip, headers, FORBIDDEN.getCode());
return;
}
try {
handleOK(channel, headers.getPath());
log(ip, headers, OK.getCode());
} catch (FileNotFoundException e) {
// 文件未發現,返回 404 錯誤
handleNotFound(channel);
log(ip, headers, NOT_FOUND.getCode());
} catch (Exception e) {
// 其他異常,返回 500 錯誤
handleInternalServerError(channel);
log(ip, headers, INTERNAL_SERVER_ERROR.getCode());
} finally {
channel.close();
}
}
// 處理正常的請求
private void handleOK(SocketChannel channel, String path) throws IOException {
ResponseHeaders headers = new ResponseHeaders(OK.getCode());
// 讀取文件
ByteBuffer bodyBuffer = readFile(path);
// 設置響應頭
headers.setContentLength(bodyBuffer.capacity());
headers.setContentType(ContentTypeUtils.getContentType(getExtension(path)));
ByteBuffer headerBuffer = ByteBuffer.wrap(headers.toString().getBytes());
// 將響應頭和資源數據一同返回
channel.write(new ByteBuffer[]{headerBuffer, bodyBuffer});
}
// 處理請求資源未發現的錯誤
private void handleNotFound(SocketChannel channel) {
try {
handleError(channel, NOT_FOUND.getCode());
} catch (Exception e) {
handleInternalServerError(channel);
}
}
private void handleError(SocketChannel channel, int statusCode) throws IOException {
ResponseHeaders headers = new ResponseHeaders(statusCode);
// 讀取文件
ByteBuffer bodyBuffer = readFile(String.format("/%d.html", statusCode));
// 設置響應頭
headers.setContentLength(bodyBuffer.capacity());
headers.setContentType(ContentTypeUtils.getContentType("html"));
ByteBuffer headerBuffer = ByteBuffer.wrap(headers.toString().getBytes());
// 將響應頭和資源數據一同返回
channel.write(new ByteBuffer[]{headerBuffer, bodyBuffer});
}
```
上面的代碼略長,不過邏輯仍然比較簡單。首先,要判斷請求頭存在,以及資源路徑是否合法。如果都合法,再去讀取資源文件,如果文件不存在,則返回 404 錯誤碼。如果發生其他異常,則返回 500 錯誤。如果沒有錯誤發生,則正常返回響應頭和資源數據。這里只貼了核心代碼,其他代碼就不貼了,大家自己去看吧。
### [](http://www.tianxiaobo.com/2018/04/04/%E5%9F%BA%E4%BA%8E-Java-NIO-%E5%AE%9E%E7%8E%B0%E7%AE%80%E5%8D%95%E7%9A%84-HTTP-%E6%9C%8D%E5%8A%A1%E5%99%A8/#23-效果演示)2.3 效果演示
分析完代碼,接下來看點輕松的吧。下面貼一張代碼的運行效果圖,如下:

## [](http://www.tianxiaobo.com/2018/04/04/%E5%9F%BA%E4%BA%8E-Java-NIO-%E5%AE%9E%E7%8E%B0%E7%AE%80%E5%8D%95%E7%9A%84-HTTP-%E6%9C%8D%E5%8A%A1%E5%99%A8/#3總結)3.總結
本文所貼的代碼是我在學習 Selector 過程中寫的,核心代碼不到 300 行。通過動手寫代碼,也使得我加深了對 Selector 的了解。在學習 JDK 的過程中,強烈建議大家多動手寫代碼。通過寫代碼,并踩一些坑,才能更加熟練運用相關技術。這個是我寫 NIO 系列文章的一個感觸
- 一.JVM
- 1.1 java代碼是怎么運行的
- 1.2 JVM的內存區域
- 1.3 JVM運行時內存
- 1.4 JVM內存分配策略
- 1.5 JVM類加載機制與對象的生命周期
- 1.6 常用的垃圾回收算法
- 1.7 JVM垃圾收集器
- 1.8 CMS垃圾收集器
- 1.9 G1垃圾收集器
- 2.面試相關文章
- 2.1 可能是把Java內存區域講得最清楚的一篇文章
- 2.0 GC調優參數
- 2.1GC排查系列
- 2.2 內存泄漏和內存溢出
- 2.2.3 深入理解JVM-hotspot虛擬機對象探秘
- 1.10 并發的可達性分析相關問題
- 二.Java集合架構
- 1.ArrayList深入源碼分析
- 2.Vector深入源碼分析
- 3.LinkedList深入源碼分析
- 4.HashMap深入源碼分析
- 5.ConcurrentHashMap深入源碼分析
- 6.HashSet,LinkedHashSet 和 LinkedHashMap
- 7.容器中的設計模式
- 8.集合架構之面試指南
- 9.TreeSet和TreeMap
- 三.Java基礎
- 1.基礎概念
- 1.1 Java程序初始化的順序是怎么樣的
- 1.2 Java和C++的區別
- 1.3 反射
- 1.4 注解
- 1.5 泛型
- 1.6 字節與字符的區別以及訪問修飾符
- 1.7 深拷貝與淺拷貝
- 1.8 字符串常量池
- 2.面向對象
- 3.關鍵字
- 4.基本數據類型與運算
- 5.字符串與數組
- 6.異常處理
- 7.Object 通用方法
- 8.Java8
- 8.1 Java 8 Tutorial
- 8.2 Java 8 數據流(Stream)
- 8.3 Java 8 并發教程:線程和執行器
- 8.4 Java 8 并發教程:同步和鎖
- 8.5 Java 8 并發教程:原子變量和 ConcurrentMap
- 8.6 Java 8 API 示例:字符串、數值、算術和文件
- 8.7 在 Java 8 中避免 Null 檢查
- 8.8 使用 Intellij IDEA 解決 Java 8 的數據流問題
- 四.Java 并發編程
- 1.線程的實現/創建
- 2.線程生命周期/狀態轉換
- 3.線程池
- 4.線程中的協作、中斷
- 5.Java鎖
- 5.1 樂觀鎖、悲觀鎖和自旋鎖
- 5.2 Synchronized
- 5.3 ReentrantLock
- 5.4 公平鎖和非公平鎖
- 5.3.1 說說ReentrantLock的實現原理,以及ReentrantLock的核心源碼是如何實現的?
- 5.5 鎖優化和升級
- 6.多線程的上下文切換
- 7.死鎖的產生和解決
- 8.J.U.C(java.util.concurrent)
- 0.簡化版(快速復習用)
- 9.鎖優化
- 10.Java 內存模型(JMM)
- 11.ThreadLocal詳解
- 12 CAS
- 13.AQS
- 0.ArrayBlockingQueue和LinkedBlockingQueue的實現原理
- 1.DelayQueue的實現原理
- 14.Thread.join()實現原理
- 15.PriorityQueue 的特性和原理
- 16.CyclicBarrier的實際使用場景
- 五.Java I/O NIO
- 1.I/O模型簡述
- 2.Java NIO之緩沖區
- 3.JAVA NIO之文件通道
- 4.Java NIO之套接字通道
- 5.Java NIO之選擇器
- 6.基于 Java NIO 實現簡單的 HTTP 服務器
- 7.BIO-NIO-AIO
- 8.netty(一)
- 9.NIO面試題
- 六.Java設計模式
- 1.單例模式
- 2.策略模式
- 3.模板方法
- 4.適配器模式
- 5.簡單工廠
- 6.門面模式
- 7.代理模式
- 七.數據結構和算法
- 1.什么是紅黑樹
- 2.二叉樹
- 2.1 二叉樹的前序、中序、后序遍歷
- 3.排序算法匯總
- 4.java實現鏈表及鏈表的重用操作
- 4.1算法題-鏈表反轉
- 5.圖的概述
- 6.常見的幾道字符串算法題
- 7.幾道常見的鏈表算法題
- 8.leetcode常見算法題1
- 9.LRU緩存策略
- 10.二進制及位運算
- 10.1.二進制和十進制轉換
- 10.2.位運算
- 11.常見鏈表算法題
- 12.算法好文推薦
- 13.跳表
- 八.Spring 全家桶
- 1.Spring IOC
- 2.Spring AOP
- 3.Spring 事務管理
- 4.SpringMVC 運行流程和手動實現
- 0.Spring 核心技術
- 5.spring如何解決循環依賴問題
- 6.springboot自動裝配原理
- 7.Spring中的循環依賴解決機制中,為什么要三級緩存,用二級緩存不夠嗎
- 8.beanFactory和factoryBean有什么區別
- 九.數據庫
- 1.mybatis
- 1.1 MyBatis-# 與 $ 區別以及 sql 預編譯
- Mybatis系列1-Configuration
- Mybatis系列2-SQL執行過程
- Mybatis系列3-之SqlSession
- Mybatis系列4-之Executor
- Mybatis系列5-StatementHandler
- Mybatis系列6-MappedStatement
- Mybatis系列7-參數設置揭秘(ParameterHandler)
- Mybatis系列8-緩存機制
- 2.淺談聚簇索引和非聚簇索引的區別
- 3.mysql 證明為什么用limit時,offset很大會影響性能
- 4.MySQL中的索引
- 5.數據庫索引2
- 6.面試題收集
- 7.MySQL行鎖、表鎖、間隙鎖詳解
- 8.數據庫MVCC詳解
- 9.一條SQL查詢語句是如何執行的
- 10.MySQL 的 crash-safe 原理解析
- 11.MySQL 性能優化神器 Explain 使用分析
- 12.mysql中,一條update語句執行的過程是怎么樣的?期間用到了mysql的哪些log,分別有什么作用
- 十.Redis
- 0.快速復習回顧Redis
- 1.通俗易懂的Redis數據結構基礎教程
- 2.分布式鎖(一)
- 3.分布式鎖(二)
- 4.延時隊列
- 5.位圖Bitmaps
- 6.Bitmaps(位圖)的使用
- 7.Scan
- 8.redis緩存雪崩、緩存擊穿、緩存穿透
- 9.Redis為什么是單線程、及高并發快的3大原因詳解
- 10.布隆過濾器你值得擁有的開發利器
- 11.Redis哨兵、復制、集群的設計原理與區別
- 12.redis的IO多路復用
- 13.相關redis面試題
- 14.redis集群
- 十一.中間件
- 1.RabbitMQ
- 1.1 RabbitMQ實戰,hello world
- 1.2 RabbitMQ 實戰,工作隊列
- 1.3 RabbitMQ 實戰, 發布訂閱
- 1.4 RabbitMQ 實戰,路由
- 1.5 RabbitMQ 實戰,主題
- 1.6 Spring AMQP 的 AMQP 抽象
- 1.7 Spring AMQP 實戰 – 整合 RabbitMQ 發送郵件
- 1.8 RabbitMQ 的消息持久化與 Spring AMQP 的實現剖析
- 1.9 RabbitMQ必備核心知識
- 2.RocketMQ 的幾個簡單問題與答案
- 2.Kafka
- 2.1 kafka 基礎概念和術語
- 2.2 Kafka的重平衡(Rebalance)
- 2.3.kafka日志機制
- 2.4 kafka是pull還是push的方式傳遞消息的?
- 2.5 Kafka的數據處理流程
- 2.6 Kafka的腦裂預防和處理機制
- 2.7 Kafka中partition副本的Leader選舉機制
- 2.8 如果Leader掛了的時候,follower沒來得及同步,是否會出現數據不一致
- 2.9 kafka的partition副本是否會出現腦裂情況
- 十二.Zookeeper
- 0.什么是Zookeeper(漫畫)
- 1.使用docker安裝Zookeeper偽集群
- 3.ZooKeeper-Plus
- 4.zk實現分布式鎖
- 5.ZooKeeper之Watcher機制
- 6.Zookeeper之選舉及數據一致性
- 十三.計算機網絡
- 1.進制轉換:二進制、八進制、十六進制、十進制之間的轉換
- 2.位運算
- 3.計算機網絡面試題匯總1
- 十四.Docker
- 100.面試題收集合集
- 1.美團面試常見問題總結
- 2.b站部分面試題
- 3.比心面試題
- 4.騰訊面試題
- 5.哈羅部分面試
- 6.筆記
- 十五.Storm
- 1.Storm和流處理簡介
- 2.Storm 核心概念詳解
- 3.Storm 單機版本環境搭建
- 4.Storm 集群環境搭建
- 5.Storm 編程模型詳解
- 6.Storm 項目三種打包方式對比分析
- 7.Storm 集成 Redis 詳解
- 8.Storm 集成 HDFS 和 HBase
- 9.Storm 集成 Kafka
- 十六.Elasticsearch
- 1.初識ElasticSearch
- 2.文檔基本CRUD、集群健康檢查
- 3.shard&replica
- 4.document核心元數據解析及ES的并發控制
- 5.document的批量操作及數據路由原理
- 6.倒排索引
- 十七.分布式相關
- 1.分布式事務解決方案一網打盡
- 2.關于xxx怎么保證高可用的問題
- 3.一致性hash原理與實現
- 4.微服務注冊中心 Nacos 比 Eureka的優勢
- 5.Raft 協議算法
- 6.為什么微服務架構中需要網關
- 0.CAP與BASE理論
- 十八.Dubbo
- 1.快速掌握Dubbo常規應用
- 2.Dubbo應用進階
- 3.Dubbo調用模塊詳解
- 4.Dubbo調用模塊源碼分析
- 6.Dubbo協議模塊