JAVA NIO จัดเตรียม API เพื่อเขียนเซิร์ฟเวอร์ TCP โดยใช้สถาปัตยกรรม NIO ดังนี้
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.text.ParseException;
import java.util.*;
public class NIOServer implements Runnable{
private InetAddress addr;
private int port;
private Selector selector;
public NIOServer(InetAddress addr, int port) throws IOException {
this.addr = addr;
this.port = port;
}
public void run(){
try {
startServer();
}catch(IOException ex){
System.out.println(ex.getMessage());
}
}
private void startServer() throws IOException {
this.selector = Selector.open();
ServerSocketChannel serverChannel = serverSocketChannel.open();
serverChannel.configureBlocking(false);
InetSocketAddress listenAddr = new InetSocketAddress(this.addr, this.port);
serverChannel.socket().bind(listenAddr);
serverChannel.register(this.selector, SelectionKey.OP_ACCEPT);
while (true) {
this.selector.select();
Iterator keys = this.selector.selectedKeys().iterator();
while (keys.hasNext()) {
SelectionKey key = (SelectionKey) keys.next();
keys.remove();
if (! key.isValid()) {
continue;
}
if (key.isAcceptable()) {
this.accept(key);
}
else if (key.isReadable()) {
this.read(key);
}
else if (key.isWritable()) {
this.write(key);
}
}
}
}
}
ซึ่งใช้เธรดเดียวที่จะประมวลผลเหตุการณ์ต่างๆ เช่น อ่าน เขียน และยอมรับ
เมื่อเปรียบเทียบกับการบล็อกเธรดต่อสถาปัตยกรรมการเชื่อมต่อ สิ่งนี้เป็นที่ต้องการมากกว่า เนื่องจากมีลักษณะไม่บล็อกซึ่งทำให้แคชพลาดขั้นต่ำ ค่าโสหุ้ยของเธรด และการย้าย CPU ต่ำ
อย่างไรก็ตาม สถาปัตยกรรมนี้ใช้เพียงเธรดเดียวเท่านั้น ในสภาพแวดล้อมที่มีหลายกระบวนการ (เช่น CPU 4 คอร์) สถาปัตยกรรม NIO จะทำให้คอร์อื่นๆ สิ้นเปลืองไป มีวิธีการออกแบบที่ฉันสามารถใช้เพื่อใช้ประโยชน์จากคอร์ทั้งหมดด้วยสถาปัตยกรรม NIO หรือไม่
NIO2 (ซึ่งขึ้นอยู่กับรูปแบบ proactor) เป็นหนึ่งในตัวเลือกดังกล่าว แต่สถาปัตยกรรมพื้นฐานนั้นแตกต่างไปจาก NIO ดั้งเดิมมาก