public class NIOServer {
private static int BUFF_SIZE=1024;
private static int TIME_OUT = 2000;
public static void main(String[] args) throws IOException {
Selector selector = Selector.open();
ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(10083));
serverSocketChannel.configureBlocking(false);
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
TCPProtocol protocol = new EchoSelectorProtocol(BUFF_SIZE);
while (true) {
if(selector.select(TIME_OUT)==0){
//在等待信道准备的同时,也可以异步地执行其他任务, 这里打印*
System.out.print("*");
continue;
}
Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();
while (keyIter.hasNext()) {
SelectionKey key = keyIter.next();
//如果服务端信道感兴趣的I/O操作为accept
if (key.isAcceptable()){
protocol.handleAccept(key);
}
//如果客户端信道感兴趣的I/O操作为read
if (key.isReadable()){
protocol.handleRead(key);
}
//如果该键值有效,并且其对应的客户端信道感兴趣的I/O操作为write
if (key.isValid() && key.isWritable()) {
protocol.handleWrite(key);
}
//这里需要手动从键集中移除当前的key
keyIter.remove();
}
}
}
}
public class NIOClient {
public static Selector selector;
public static SocketChannel clntChan;
static {
try {
selector = Selector.open();
clntChan = SocketChannel.open();
clntChan.configureBlocking(false);
clntChan.connect(new InetSocketAddress("localhost", 10083));
clntChan.register(selector, SelectionKey.OP_READ);
while (!clntChan.finishConnect()){
}
System.out.println("已连接!");
}catch (Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
SocketChannel socketChannel = NIOClient.clntChan;
ByteBuffer byteBuffer = ByteBuffer.allocate(256);
new Avca(selector,socketChannel).start();
while (true){
Scanner scanner = new Scanner(System.in);
String word = scanner.nextLine();
byteBuffer.put(word.getBytes());
byteBuffer.flip();
socketChannel.write(byteBuffer);
byteBuffer.clear();
}
}
static class Avca extends Thread{
private Selector selector;
private SocketChannel clntChan;
public Avca(Selector selector,SocketChannel clntChan){
this.selector = selector;
this.clntChan = clntChan;
}
@Override
public void run(){
try {
while (true){
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> keyIterator = keys.iterator();
ByteBuffer byteBuffer = ByteBuffer.allocate(256);
while (keyIterator.hasNext()){
SelectionKey selectionKey = keyIterator.next();
if (selectionKey.isValid()){
if (selectionKey.isReadable()){
SocketChannel socketChannel = (SocketChannel)selectionKey.channel();
socketChannel.read(byteBuffer);
byteBuffer.flip();
byte[] bytes = new byte[byteBuffer.remaining()];
byteBuffer.get(bytes);
System.out.println(new String(bytes));
byteBuffer.clear();
}
}
}
}
}catch (Exception e){
e.printStackTrace();
}
}
}
}