Java NIO通俗程式設計之選擇器Selector(四)
阿新 • • 發佈:2019-02-13
最後一步就是根據不同的事件,編寫相應的處理程式碼:
此處分別判斷是接受請求、讀資料還是寫事件,分別作不同的處理。/* * 根據不同的事件做處理 * */ protected void process(SelectionKey key) throws IOException{ // 接收請求 if (key.isAcceptable()) { ServerSocketChannel server = (ServerSocketChannel) key.channel(); SocketChannel channel = server.accept(); channel.configureBlocking(false); channel.register(selector, SelectionKey.OP_READ); } // 讀資訊 else if (key.isReadable()) { SocketChannel channel = (SocketChannel) key.channel(); int count = channel.read(buffer); if (count > 0) { buffer.flip(); CharBuffer charBuffer = decoder.decode(buffer); name = charBuffer.toString(); SelectionKey sKey = channel.register(selector, SelectionKey.OP_WRITE); sKey.attach(name); } else { channel.close(); } buffer.clear(); } // 寫事件 else if (key.isWritable()) { SocketChannel channel = (SocketChannel) key.channel(); String name = (String) key.attachment(); ByteBuffer block = encoder.encode(CharBuffer.wrap("Hello " + name)); if(block != null) { channel.write(block); } else { channel.close(); } } }