package com.cctv.http.nio;
import sun.security.action.GetPropertyAction;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.security.AccessController;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* @Title:
* @BelongProjecet http-demo
* @Description:
* @Author: lingchuan
* @Date: 2020-04-27 16:09
*/
public class NioHttpServer {
public static volatile ConcurrentMap<Channel, String> req = new ConcurrentHashMap();
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) {
int result = selector.selectNow();
if (result == 0) {
continue;
}
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> it = selectionKeys.iterator();
while (it.hasNext()) {
SelectionKey selectionKey = it.next();
handleInput(selectionKey);
it.remove();
}
}
}
private static void handleInput(SelectionKey key) throws IOException {
if (key.isAcceptable()) {
doAccep(key);
}
if (key.isReadable()) {
doRead(key);
}
if (key.isWritable()) {
doWrite(key);
}
}
private static void doAccep(SelectionKey key) throws IOException {
SocketChannel channel = ((ServerSocketChannel) key.channel()).accept();
channel.configureBlocking(false);
channel.register(key.selector(), SelectionKey.OP_READ);
}
private static void doRead(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(4);
String requestData = "";
int eof = channel.read(buffer);
System.out.println("读入" + eof + "字节");
if (eof > 0) {
buffer.flip();
CharBuffer cb = Charset.forName("UTF-8").decode(buffer);
requestData += cb.toString();
buffer.clear();
if (key.attachment() != null) {
key.attach(key.attachment() + requestData);
} else {
key.attach(requestData);
}
} else {
System.out.println("读完毕");
key.interestOps(SelectionKey.OP_WRITE);
}
}
private static void doWrite(SelectionKey key)
throws IOException {
SocketChannel channel = (SocketChannel) key.channel();
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("200 OK\n");
stringBuffer.append("Content-Type: text/html; charset=UTF-8\n");
stringBuffer.append("Received:" + key.attachment());
stringBuffer.append("\n");
String response = stringBuffer.toString();
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);
}
key.cancel();
channel.close();
}
}
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.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-05-12 17:06
*/
public class NioClient {
public static void main(String[] args) throws IOException {
Selector selector = Selector.open();
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
socketChannel.connect(new InetSocketAddress("127.0.0.1", 8080));
socketChannel.register(selector, SelectionKey.OP_CONNECT);
while (true) {
int result = selector.selectNow();
if (result == 0) {
continue;
}
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> it = selectionKeys.iterator();
while (it.hasNext()) {
SelectionKey selectionKey = it.next();
handleInput(selectionKey);
it.remove();
}
}
}
private static void handleInput(SelectionKey key) throws IOException {
if (key.isConnectable()) {
SocketChannel channel = (SocketChannel) key.channel();
System.out.println(channel.finishConnect());
key.interestOps(SelectionKey.OP_WRITE);
}
if (key.isAcceptable()) {
}
if (key.isReadable()) {
doRead(key);
}
if (key.isWritable()) {
doWrite(key);
key.interestOps(SelectionKey.OP_READ);
}
}
private static void doRead(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(4);
String requestData = "";
int eof = channel.read(buffer);
if (eof >= 0) {
System.out.println("继续读:" + eof);
buffer.flip();
CharBuffer cb = Charset.forName("UTF-8").decode(buffer);
requestData += cb.toString();
buffer.clear();
if (key.attachment() != null) {
key.attach(key.attachment() + requestData);
} else {
key.attach(requestData);
}
}
if (eof == -1) {
System.out.println(key.attachment());
if (key.isValid()) {
key.cancel();
channel.close();
System.exit(1);
}
}
}
private static void doWrite(SelectionKey key) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
byte[] req = "Hello Server".getBytes();
ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
writeBuffer.put(req);
writeBuffer.flip();
socketChannel.write(writeBuffer);
socketChannel.shutdownOutput();
}
}