package com.test1;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
public class HttpServer {
public static void main(String[] args) throws Exception{
ServerSocketChannel ssc=ServerSocketChannel.open();
ssc.socket().bind(new InetSocketAddress(8082));
ssc.configureBlocking(false);
Selector selector=Selector.open();
ssc.register(selector, SelectionKey.OP_ACCEPT);
while(true) {
if(selector.select(3000)==0) {
continue;
}
Iterator<SelectionKey> keyIter=selector.selectedKeys().iterator();
while(keyIter.hasNext()) {
SelectionKey key=keyIter.next();
new Thread(new HttpHandler(key)).run();
keyIter.remove();
}
}
}
}
package com.test1;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
public class HttpHandler implements Runnable{
private int bufferSize=1024;
private String localCharset="UTF-8";
public SelectionKey key;
public HttpHandler(SelectionKey key) {
this.key=key;
}
public void handleAccept() throws IOException{
SocketChannel sc=((ServerSocketChannel) key.channel()).accept();
sc.configureBlocking(false);
sc.register(key.selector(), SelectionKey.OP_READ,ByteBuffer.allocate(bufferSize));
}
public void handleRead(SelectionKey key) throws IOException{
SocketChannel clientChannel=(SocketChannel) key.channel();
clientChannel.configureBlocking(false);
clientChannel.register(key.selector(), SelectionKey.OP_READ,ByteBuffer.allocate(bufferSize));
}
public void handleRead() throws IOException{
SocketChannel sc=(SocketChannel) key.channel();
ByteBuffer buffer=(ByteBuffer) key.attachment();
buffer.clear();
if(sc.read(buffer)==-1) {
sc.close();
}else {
buffer.flip();
String receivedString =Charset.forName(localCharset).newDecoder().decode(buffer).toString();
String[] requestMessge=receivedString.split("\r\n");
for(String s:requestMessge) {
System.out.println(s);
if(s.isEmpty()) {
break;
}
String[] firstLine=requestMessge[0].split("");
System.out.println();
System.out.println("Methid:\t"+firstLine[0]);
System.out.println("url:\t"+firstLine[1]);
System.out.println("HTTP Version:\t"+firstLine[2]);
System.out.println();
StringBuilder sendString =new StringBuilder();
sendString.append("HTTP/1.1 200 Ok\r\n");
sendString.append("localCharset"+localCharset+"\r\n");
sendString.append("\r\n");
sendString.append("<html><head><title>显示报文</title></head><body>");
sendString.append("接收到请求报文是:<br/>");
for(String s1:requestMessge) {
sendString.append(s1+"<br/>");
}
sendString.append("<body></html>");
buffer=ByteBuffer.wrap(sendString.toString().getBytes(localCharset));
sc.write(buffer);
sc.close();
}
}
}
public void run() {
try {
if (key.isAcceptable()) {
handleAccept();
}
if (key.isReadable()) {
handleRead();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}