NIO的简单Demo
package jesse.test1; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; import java.util.Iterator; import java.util.Set; public class NIOServer extends Thread{ @Override public void run(){ try { // 1,创建Selector 和 Channel Selector selector = Selector.open(); ServerSocketChannel serverSocket = ServerSocketChannel.open(); // serverSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(), 8888)); serverSocket.configureBlocking(false); // 注册到Selector,并说明关注点 serverSocket.register(selector, SelectionKey.OP_ACCEPT); while(true){ //阻塞等待就绪的Channel selector.select(); Set<SelectionKey> selectedKeys = selector.selectedKeys(); Iterator<SelectionKey> iter = selectedKeys.iterator(); while(iter.hasNext()){ SelectionKey key = iter.next(); // 生产中一般会额外进行就绪状态检查 sayHelloWorld((ServerSocketChannel) key.channel()); iter.remove(); } } } catch (IOException e) { e.printStackTrace(); } } private void sayHelloWorld(ServerSocketChannel server){ try { SocketChannel client = server.accept(); client.write(Charset.defaultCharset().encode("hello World.")); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { /*NIOServer server = new NIOServer(); server.start(); try { Socket client = new Socket(InetAddress.getLocalHost(), 8888); BufferedReader bufferReader = new BufferedReader(new InputStreamReader(client.getInputStream())); System.out.println(bufferReader.readLine()); } catch (IOException e) { e.printStackTrace(); }*/ System.out.println("hello world"); ThreadGroup group = Thread.currentThread().getThreadGroup(); ThreadGroup topGroup = group; while (group != null) { topGroup = group; group = group.getParent(); } int nowThreads = topGroup.activeCount(); Thread[] lstThreads = new Thread[nowThreads]; topGroup.enumerate(lstThreads); for (int i = 0; i < nowThreads; i++) { System.out.println("线程number:" + i + " = " + lstThreads[i].getName()); } } } /** * 1、通过Selector.open 创建Selector,类似调度员 * 2、创建一个ServerSocketChannel,并且注册到Selector上,指定SelectionKey.OP_ACCEPT,接收新的连接请求 * 3、Selector阻塞在select请求,当有Channel发生接入请求,会被唤醒 * 4、通过SocketChannel和Buffer进行数据操作, */