Java NIO搭建简易HTTP服务器

package com.cctv.http.nio;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;

/**
 * @Title:
 * @BelongProjecet http-demo
 * @BelongPackage com.cctv.http.nio
 * @Description:
 * @Copyright CCTV.com
 * @Author: lingchuan
 * @Date: 2020-04-27 16:09
 */
public class NioHttpServer {
    public static void main(String[] args) throws IOException {

        Selector selector = Selector.open();

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(8080), 1024);
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);


        while (true) {
            selector.selectNow();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> it = selectionKeys.iterator();
            while (it.hasNext()) {
                SelectionKey selectionKey = it.next();
                it.remove();
                handleInput(selector, selectionKey);
            }
        }


    }

    private static void handleInput(Selector selector, SelectionKey key) throws IOException {

        // 处理新接入的请求消息
        if (key.isAcceptable()) {
            SocketChannel socketChannel = ((ServerSocketChannel) key.channel()).accept();
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ);
            System.out.println("开启链接");
        }
        if (key.isReadable()) {

            System.out.println("开始读");

            SocketChannel socketChannel = (SocketChannel) key.channel();

            ByteBuffer buffer = ByteBuffer.allocate(4);

            String requestData = "";

            while (socketChannel.read(buffer) > 0) {
                buffer.flip();
                CharBuffer cb = Charset.forName("UTF-8").decode(buffer);
                requestData+=cb.toString();
                buffer.clear();
            }

            System.out.println(requestData);


            socketChannel.register(selector, SelectionKey.OP_WRITE);


        }
        if (key.isWritable()) {
            SocketChannel socketChannel = (SocketChannel) key.channel();
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("HTTP/1.1 200 OK\n");
            stringBuffer.append("Content-Type: text/html; charset=UTF-8\n");
            stringBuffer.append("\n");
            stringBuffer.append("It's Work!");
            doWrite(socketChannel, stringBuffer.toString());
            key.cancel();
            socketChannel.close();
        }
    }

    private static void doWrite(SocketChannel channel, String response)
            throws IOException {
        System.out.println("开启写");
        if (response != null && response.trim().length() > 0) {
            byte[] bytes = response.getBytes();
            ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
            writeBuffer.put(bytes);
            writeBuffer.flip();
            channel.write(writeBuffer);
        }
        System.out.println("写完毕");
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值