package io;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Selector;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;
public class NioServer {
private Selector selector;
private ServerSocketChannel serverSocketChannel;
private ByteBuffer readBuffer = ByteBuffer.allocate(1024);
private String str;
public NioServer(int port) throws IOException {
this.serverSocketChannel = ServerSocketChannel.open();
this.serverSocketChannel.configureBlocking(false);
this.serverSocketChannel.bind(new InetSocketAddress(port));
this.selector = Selector.open();
this.serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}
public void handle() throws IOException {
while(!Thread.currentThread().isInterrupted()) {
if(selector.select() == 0) {
continue;
}
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> keyIterator = keys.iterator();
while(keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
if(!key.isValid()) {
continue;
}
if(key.isAcceptable()) {
accept(key);
}
if(key.isReadable()) {
read(key);
}
keyIterator.remove();
}
}
}
public void accept(SelectionKey key) throws IOException {
SocketChannel socketChannel = this.serverSocketChannel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
System.out.println("client connected " + socketChannel.getRemoteAddress());
}
private void read(SelectionKey key) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
this.readBuffer.clear();
int numRead;
try {
numRead = socketChannel.read(this.readBuffer);
} catch(IOException ex) {
System.out.println("read failed");
key.cancel();
socketChannel.close();
return;
}
str = new String(readBuffer.array(), 0, numRead);
System.out.println("read String is: " + str);
String response = "HTTP/1.1 200 OK\r\n" +
"Content-Type: text/plain\r\n" +
"Content-Length: 13\r\n" +
"\r\n" +
"Hello, World!";
ByteBuffer responseBuffer = ByteBuffer.wrap(response.getBytes());
socketChannel.write(responseBuffer);
socketChannel.close();
}
public static void main(String[] args) throws IOException {
System.out.println("Hello, NioServer...");
new NioServer(8899).handle();
}
}
浏览器请求localhost:8899,返回hello,world