• 一段关于java NIO server端接受客户端socket连接;演示了关于channel,selector等组件的整合使用


    public class ReactorDemo {
    
        public static void main(String[] args) throws IOException {
            ServerSocketChannel ssc = ServerSocketChannel.open();//管道型ServerSocket
            ssc.socket().bind(new InetSocketAddress("127.0.0.1", 8089));
            ssc.configureBlocking(false);//设置非阻塞
            System.out.println(" NIO single server started, listening on :" + ssc.getLocalAddress());
            Selector selector = Selector.open();
            ssc.register(selector, SelectionKey.OP_ACCEPT);//在建立好的管道上,注册关心的事件 就绪
            while(true) {
                selector.select();
                Set<SelectionKey> keys = selector.selectedKeys();
                Iterator<SelectionKey> it = keys.iterator();
                while(it.hasNext()) {
                    SelectionKey key = it.next();
                    it.remove();//处理的事件,必须删除
                    handle(key);
                }
            }
        }
        private static void handle(SelectionKey key) throws IOException {
            if(key.isAcceptable()) {//测试通道是否准备好接受新的套接字连接。
                System.out.println("accept occur...");
                ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                SocketChannel sc = ssc.accept();
                sc.configureBlocking(false);//设置非阻塞
                sc.register(key.selector(), SelectionKey.OP_READ );//在建立好的管道上,注册关心的事件 可读
            } else if (key.isReadable()) { //测试通道是否可以读取
                System.out.println("readable occur ...");
                SocketChannel sc = null;
                sc = (SocketChannel)key.channel();
                ByteBuffer buffer = ByteBuffer.allocate(512);
                buffer.clear();
                int len = sc.read(buffer);
                if(len != -1) {
                    System.out.println("[" +Thread.currentThread().getName()+"] recv :"+ new String(buffer.array(), 0, len));
                }
                ByteBuffer bufferToWrite = ByteBuffer.wrap("HelloClient".getBytes());
                sc.write(bufferToWrite);
            }else if(key.isWritable()){
                System.out.println("write able occur...");
            }
        }
    }
  • 相关阅读:
    课后作业 学号15100457
    开学第一课
    20180320作业2:进行代码复审训练
    20180320作业1:源代码管理工具调查
    软工作业PSP与单元测试训练
    构建之法 完成教材第一章P18第4题
    第一天上课 创建博客
    进行代码复审训练
    源代码管理工具调查
    软工作业PSP与单元测试训练
  • 原文地址:https://www.cnblogs.com/StarbucksBoy/p/14463975.html
Copyright © 2020-2023  润新知