首页  

第一个 NIO server 例子     所属分类 nio 浏览量 52
第一个NIO server 
telnet 连接 发送数据
观察 连接 和 读取事件处理 


缓冲区大小8
数据没读完会一直触发读操作
telnet 127.0.0.1 8070
输入  123 ( 实际发送 123\r\n  5个字节),服务端触发一次读操作 ,读取到5字节
输入  1234567 ( 实际发送 1234567\r\n  9个字节)服务端触发2次读操作 ,分别读取到 8字节和1字节
Telnet 强制关闭后 读取到 -1 ,连接关闭





Selector selector = Selector.open();
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(port), 1024);
// nonblocking
serverSocketChannel.configureBlocking(false);
// 注册 ACCEPT 事件,监听连接事件
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        
while (true) {
    int selectorResult = 0;
    // selectNow 非阻塞 ,无就绪事件 直接返回 0
    // Selects a set of keys whose corresponding channels are ready for I/O operations
    // selectorResult = selector.selectNow();
    // selectNow 阻塞版本 ,有就绪事件才返回
    selectorResult = selector.select();
    System.out.println("selectorResult="+selectorResult);
    Set<SelectionKey> selectionKeys = selector.selectedKeys();
    System.out.println("selectionKeys.count="+selectionKeys.size());

    Iterator<SelectionKey> it = selectionKeys.iterator();
    while (it.hasNext()) {
        SelectionKey selectionKey = it.next();
        it.remove();
        handle(selector, selectionKey);
    }
}   


    private static void handle(Selector selector, SelectionKey key) throws IOException {
 
        if (key.isAcceptable()) {
            SocketChannel socketChannel = ((ServerSocketChannel) key.channel()).accept();
            socketChannel.configureBlocking(false);
            // ByteBuffer buffer = ByteBuffer.allocate(1024 * 8);
            ByteBuffer buffer = ByteBuffer.allocate(8);
            // 连接之后 注册读事件
            socketChannel.register(selector, SelectionKey.OP_READ,buffer);
            System.out.println("Accept done,socketChannel="+socketChannel);
        }
        if (key.isReadable()) {
        	
            SocketChannel socketChannel = (SocketChannel) key.channel();
        	ByteBuffer buffer = (ByteBuffer)key.attachment();
        	buffer.clear();
            int readBytes = socketChannel.read(buffer);
        	System.out.println(readBytes+","+socketChannel);
        	if(readBytes>0) {
            	totalReadBytes.addAndGet(readBytes);          	
            	// 数据没读完会一直触发读操作
            	// 缓冲区大小8 
            	// telnet 127.0.0.1 8070
            	// 输入  123 ( 实际发送 123\r\n  5个字节),服务端触发一次读操作 ,读取到5字节
            	// 输入  1234567 ( 实际发送 1234567\r\n  9个字节)服务端触发2次读操作 ,分别读取到 8字节和1字节
            	// Telnet 强制关闭后 读取到 -1 ,连接关闭
            	return;   	
        	}
        	socketChannel.close();
            System.out.println("socketChannel close,socketChannel="+socketChannel);
            
        }
          
    }

 


完整代码
https://gitee.com/dyyx/hellocode/blob/master/src/nio/SimpleNioServer.java

上一篇     下一篇
G1调优建议

检查硬盘是否为SSD

NIO概述

Java NIO 注意点

Java NIO写事件处理技巧

java NIO buffer