|
| 1 | +package nio.myself; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.net.InetSocketAddress; |
| 5 | +import java.nio.ByteBuffer; |
| 6 | +import java.nio.channels.SelectionKey; |
| 7 | +import java.nio.channels.Selector; |
| 8 | +import java.nio.channels.ServerSocketChannel; |
| 9 | +import java.nio.channels.SocketChannel; |
| 10 | +import java.util.Set; |
| 11 | + |
| 12 | +/** |
| 13 | + * Created by szh on 2017/5/3. |
| 14 | + */ |
| 15 | +public class MyServer { |
| 16 | + public void startServer() throws IOException { |
| 17 | + ServerSocketChannel serverSocketChannel= ServerSocketChannel.open(); |
| 18 | + serverSocketChannel.bind(new InetSocketAddress(9002)); |
| 19 | + Selector selector =Selector.open(); // 打开选择器 |
| 20 | + serverSocketChannel.configureBlocking(false); |
| 21 | + serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); // 将新进来的通道注册到选择器当中 |
| 22 | + while (true){ |
| 23 | + selector.select(); |
| 24 | + Set<SelectionKey> selectionKeys =selector.selectedKeys(); |
| 25 | + for(SelectionKey selectionKey : selectionKeys){ |
| 26 | + if(selectionKey.isAcceptable()){ |
| 27 | + ServerSocketChannel ssc = (ServerSocketChannel) selectionKey.channel(); |
| 28 | + SocketChannel socketChannel =ssc.accept(); // 返回SocketChannel ,非阻塞模式下会立即返回 |
| 29 | + socketChannel.configureBlocking(false); // 非阻塞IO |
| 30 | + socketChannel.register(selector,selectionKey.OP_READ); |
| 31 | + }else if(selectionKey.isReadable()){ |
| 32 | + SocketChannel socketChannel = (SocketChannel) selectionKey.channel(); |
| 33 | + ByteBuffer byteBuffer =ByteBuffer.allocate(1024); |
| 34 | + socketChannel.read(byteBuffer); |
| 35 | + byteBuffer.flip(); |
| 36 | + socketChannel.write(byteBuffer); |
| 37 | + } |
| 38 | + } |
| 39 | + selectionKeys.clear(); |
| 40 | + } |
| 41 | + } |
| 42 | + public static void main(String args[]) throws IOException { |
| 43 | + new MyServer().startServer(); |
| 44 | + } |
| 45 | + |
| 46 | +} |
0 commit comments