【NIO】NIO实现HTTP服务器

简介: 【NIO】NIO实现HTTP服务器
  • NIO 实现的HTTP服务器

/**
 * NIO实现HTTP服务器
 *
 * @author futao
 * @date 2020/7/10
 */
@Slf4j
public class NioHttpServer {
    private static final ByteBuffer READ_BUFFER = ByteBuffer.allocate(1024 * 4);
    /**
     * 静态资源路径
     */
    private static final String STATIC_RESOURCE_PATH = System.getProperty("user.dir") + "/practice/src/main/resources/pages/";
    /**
     * 响应的基础信息
     */
    public static final String BASIC_RESPONSE = "HTTP/1.1 200 OK\r\n" +
            "Content-Type: text/html;charset=utf-8\r\n" +
            "Vary: Accept-Encoding\r\n";
    /**
     * 回车换行符
     */
    private static final String carriageReturn = "\r\n";
    public void start() {
        try {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.bind(new InetSocketAddress("localhost", Constants.SERVER_PORT));
            Selector selector = Selector.open();
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            while (true) {
                int eventCountTriggered = selector.select();
                if (eventCountTriggered == 0) {
                    continue;
                }
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                for (SelectionKey selectionKey : selectionKeys) {
                    handleSelectKey(selectionKey, selector);
                }
                selectionKeys.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void handleSelectKey(SelectionKey selectionKey, Selector selector) {
        if (selectionKey.isAcceptable()) {
            ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
            try {
                SocketChannel socketChannel = serverSocketChannel.accept();
                socketChannel.configureBlocking(false);
                socketChannel.register(selector, SelectionKey.OP_READ);
                log.debug("客户端[{}]接入", socketChannel.socket().getPort());
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (selectionKey.isReadable()) {
            READ_BUFFER.clear();
            SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
            try {
                while (socketChannel.read(READ_BUFFER) > 0) {
                }
                READ_BUFFER.flip();
                String requestMessage = String.valueOf(Constants.CHARSET.decode(READ_BUFFER));
                log.info("接收到浏览器发来的数据:\n{} === request print end...", requestMessage);
                if (StringUtils.isBlank(requestMessage)) {
                    selectionKey.cancel();
                    selector.wakeup();
                }
                String requestUri = NioHttpServer.getRequestUri(requestMessage);
                staticHandler(requestUri, socketChannel);
                selectionKey.cancel();
                selector.wakeup();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 获取请求的资源地址
     *
     * @param request
     * @return
     */
    private static String getRequestUri(String request) {
        //GET /index.html HTTP/1.1
        int firstBlank = request.indexOf(" ");
        String excludeMethod = request.substring(firstBlank + 2);
        return excludeMethod.substring(0, excludeMethod.indexOf(" "));
    }
    /**
     * 静态资源处理器
     *
     * @return
     */
    public boolean staticHandler(String page, SocketChannel socketChannel) throws IOException {
        //资源的绝对路径
        String filePath = NioHttpServer.STATIC_RESOURCE_PATH + page;
        boolean fileExist = false;
        File file = new File(filePath);
        if (file.exists() && file.isFile()) {
            log.debug("静态资源[{}]存在", page);
            fileExist = true;
            //读取文件内容
            byte[] bytes = Files.readAllBytes(Paths.get(filePath));
            ByteBuffer buffer = ByteBuffer.allocate(4 * 1024);
            buffer.put(BASIC_RESPONSE.getBytes(Constants.CHARSET));
            buffer.put(("Server: futaoServerBaseNIO/1.1" + NioHttpServer.carriageReturn).getBytes(Constants.CHARSET));
            buffer.put(("content-length: " + bytes.length + NioHttpServer.carriageReturn).getBytes(Constants.CHARSET));
            buffer.put(NioHttpServer.carriageReturn.getBytes(Constants.CHARSET));
            buffer.put(bytes);
            buffer.flip();
            while (buffer.hasRemaining()) {
                socketChannel.write(buffer);
            }
        }
        return fileExist;
    }
    public static void main(String[] args) {
        new NioHttpServer().start();
    }
}


  • 测试

image.png

image.png

image.png

# 源代码



# 系列文章


相关文章
|
1月前
|
网络协议 Shell 网络安全
实验目的1.编译安装httpd2.优化路径3.并将鲜花网站上传到web服务器为网页目录4.在客户机访问网站http://www.bdqn.com
实验目的1.编译安装httpd2.优化路径3.并将鲜花网站上传到web服务器为网页目录4.在客户机访问网站http://www.bdqn.com
163 0
|
2天前
|
XML Java 数据格式
Servlet 教程 之 Servlet 服务器 HTTP 响应 3
`Servlet`教程示例展示了如何创建一个HTTP响应,使用`@WebServlet(&quot;/Refresh&quot;)`的`Refresh`类继承`HttpServlet`。在`doGet`方法中,设置了`Refresh`头以每5秒自动刷新,并用`setContentType(&quot;text/html;charset=UTF-8&quot;)`设定内容类型。还使用`Calendar`和`SimpleDateFormat`获取并格式化当前时间显示。相应的`web.xml`配置指定了Servlet路径。当访问此Servlet时,页面将每5秒更新一次显示的系统时间。
14 4
|
11天前
|
域名解析 网络协议 应用服务中间件
阿里云服务器配置免费https服务
阿里云服务器配置免费https服务
|
1月前
|
Shell Linux 网络安全
【Shell 命令集合 网络通讯 】Linux 管理Apache HTTP服务器 httpd命令 使用指南
【Shell 命令集合 网络通讯 】Linux 管理Apache HTTP服务器 httpd命令 使用指南
30 0
|
1月前
|
Shell Linux Apache
【Shell 命令集合 网络通讯 】Linux 管理Apache HTTP服务器 apachectl命令 使用教程
【Shell 命令集合 网络通讯 】Linux 管理Apache HTTP服务器 apachectl命令 使用教程
162 1
|
1月前
|
数据采集 缓存 前端开发
http和https请求服务器的时候在请求头部分都带什么到服务器呢?
HTTP和HTTPS请求头基本结构相似,HTTPS多了一层SSL/TLS加密。常见请求头如Accept(指定内容类型)、Authorization(身份验证)、Cookie(会话跟踪)、User-Agent(标识用户代理)等。HTTPS特有的头包括Upgrade-Insecure-Requests(升级到HTTPS)、Strict-Transport-Security(强制使用HTTPS)、Sec-Fetch-*(安全策略)和X-Content-Type-Options、X-Frame-Options等(增强安全性)。实际应用中,请求头会根据需求和安全策略变化。
20 0
|
1月前
|
JSON 缓存 中间件
Go语言网络编程:深入探索HTTP服务器开发
【2月更文挑战第12天】本文将详细探讨使用Go语言开发HTTP服务器的过程,包括HTTP协议的理解、Go标准库中`net/http`包的使用、路由处理、中间件、静态文件服务、JSON处理以及性能优化等方面。通过本文,读者将能够掌握构建高效、可扩展HTTP服务器的关键技术。
|
1月前
|
网络安全 Apache PHP
Liunx服务器如何配置https(二)
Liunx服务器如何配置https(二)
35 0
Liunx服务器如何配置https(二)
|
1月前
|
Apache
Liunx服务器如何配置https(一)
Liunx服务器如何配置https(一)
32 0
Liunx服务器如何配置https(一)
|
1月前
|
弹性计算 网络安全 Apache
windows server2012服务器下PHPstudy配置ssl证书(https配置)
windows server2012服务器下PHPstudy配置ssl证书(https配置)
69 0