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("写完毕");
}
}