Java解读NIO Socket非堵塞形式ITeye - 牛牛娱乐

Java解读NIO Socket非堵塞形式ITeye

2019年03月01日11时36分28秒 | 作者: 寻桃 | 标签: 堵塞,形式,咱们 | 浏览: 442

Java解读NIO Socket非堵塞形式

nio 是java nonblocking(非堵塞) IO 的简称,在jdk1.4 里供给的新api 。Sun 官方标榜的特性如下: 为一切的原始类型供给(Buffer)缓存支撑。字符集编码解码处理方案。 Channel :一个新的原始I/O 笼统。 支撑锁和内存映射文件的文件拜访接口。 供给多路(non-bloking) 非堵塞式的高伸缩性网络I/O 。

缓冲区
描绘
Buffer 方位,边界和容量;
铲除,回转,重绕和符号/重置
ByteBuffer Get/put,紧缩,检查;分配,包装
MappedByteBuffer 映射到文件的字节缓冲区
CharBuffer Get/put,紧缩;分配,包装
DoubleBuffer
FloatBuffer
IntBuffer
LongBuffer
ShortBuffer
ByteOrder 字节次序的类型安全的枚举

 

NIO首要原理和适用

NIO 有一个首要的类Selector,这个相似一个观察者,只需咱们把需求探知的socketchannel告诉Selector,咱们接着做其他工作,当有 工作发作时,他会告诉咱们,传回一组SelectionKey,咱们读取这些Key,就会取得咱们刚刚注册过的socketchannel,然后,咱们从 这个Channel中读取数据,定心,包准能够读到,接着咱们能够处理这些数据。

Selector内部原理实践是在做一个对所注册的channel的轮询拜访,不断的轮询(现在就这一个算法),一旦轮询到一个channel有所注册的工作发作,比方数据来了,他就会站起来陈述,交出一把钥匙,让咱们经过这把钥匙来读取这个channel的内容。

jdk供的无堵塞I/O(NIO)有用处理了多线程效劳器存在的线程开支问题,但在运用上略显得杂乱一些。在NIO中运用多线程,首要意图已不是为了应对 每个客户端恳求而分配独立的效劳线程,而是经过多线程充沛运用用多个CPU的处理才能和处理中的等待时间,到达进步效劳才能的意图。


从最简略的Hello World开端,client多线程恳求server端,server接纳client的姓名,并回来Hello! +姓名的字符格局给client。当然实践使用并不这么简略,实践可能是拜访文件或许数据库获取信息回来给client。非堵塞的NIO有何奥秘之处?

1)server端代码

public class HelloWorldServer {  
 
    static int BLOCK = 1024;  
    static String name = "";  
    protected Selector selector;  
    protected ByteBuffer clientBuffer = ByteBuffer.allocate(BLOCK);  
    protected CharsetDecoder decoder;  
    static CharsetEncoder encoder = Charset.forName("GB2312").newEncoder();  
 
    public HelloWorldServer(int port) throws IOException {  
        selector = this.getSelector(port);  
        Charset charset = Charset.forName("GB2312");  
        decoder = charset.newDecoder();  
    }  
 
    // 获取Selector  
    protected Selector getSelector(int port) throws IOException {  
        ServerSocketChannel server = ServerSocketChannel.open();  
        Selector sel = Selector.open();  
        server.socket().bind(new InetSocketAddress(port));  
        server.configureBlocking(false);  
        server.register(sel, SelectionKey.OP_ACCEPT);  
        return sel;  
    }  
 
    // 监听端口  
    public void listen() {  
        try {  
            for (;;) {  
                selector.select();  
                Iterator iter = selector.selectedKeys().iterator();  
                while (iter.hasNext()) {  
                    SelectionKey key = (SelectionKey) iter.next();  
                    iter.remove();  
                    process(key);  
                }  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
 
    // 处理工作  
    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(clientBuffer);  
            if (count 0) {  
                clientBuffer.flip();  
                CharBuffer charBuffer = decoder.decode(clientBuffer);  
                name = charBuffer.toString();  
                // System.out.println(name);  
                SelectionKey sKey = channel.register(selector,  
                        SelectionKey.OP_WRITE);  
                sKey.attach(name);  
            } else {  
                channel.close();  
            }  
 
            clientBuffer.clear();  
        } else if (key.isWritable()) { // 写工作  
            SocketChannel channel = (SocketChannel) key.channel();  
            String name = (String) key.attachment();  
              
            ByteBuffer block = encoder.encode(CharBuffer  
                    .wrap("Hello !" + name));  
              
 
            channel.write(block);  
 
            //channel.close();  
 
        }  
    }  
 
    public static void main(String[] args) {  
        int port = 8888;  
        try {  
            HelloWorldServer server = new HelloWorldServer(port);  
            System.out.println("listening on " + port);  
              
            server.listen();  
              
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  

2)client端代码

public class HelloWorldClient {  
 
    static int SIZE = 10;  
    static InetSocketAddress ip = new InetSocketAddress("localhost", 8888);  
    static CharsetEncoder encoder = Charset.forName("GB2312").newEncoder();  
 
    static class Message implements Runnable {  
        protected String name;  
        String msg = "";  
 
        public Message(String index) {  
            this.name = index;  
        }  
 
        public void run() {  
            try {  
                long start = System.currentTimeMillis();  
                //翻开Socket通道  
                SocketChannel client = SocketChannel.open();  
                //设置为非堵塞形式  
                client.configureBlocking(false);  
                //翻开选择器  
                Selector selector = Selector.open();  
                //注册衔接效劳端socket动作  
                client.register(selector, SelectionKey.OP_CONNECT);  
                //衔接  
                client.connect(ip);  
                //分配内存  
                ByteBuffer buffer = ByteBuffer.allocate(8 * 1024);  
                int total = 0;  
 
                _FOR: for (;;) {  
                    selector.select();  
                    Iterator iter = selector.selectedKeys().iterator();  
 
                    while (iter.hasNext()) {  
                        SelectionKey key = (SelectionKey) iter.next();  
                        iter.remove();  
                        if (key.isConnectable()) {  
                            SocketChannel channel = (SocketChannel) key  
                                    .channel();  
                            if (channel.isConnectionPending())  
                                channel.finishConnect();  
                            channel  
                                    .write(encoder  
                                            .encode(CharBuffer.wrap(name)));  
 
                            channel.register(selector, SelectionKey.OP_READ);  
                        } else if (key.isReadable()) {  
                            SocketChannel channel = (SocketChannel) key  
                                    .channel();  
                            int count = channel.read(buffer);  
                            if (count 0) {  
                                total += count;  
                                buffer.flip();  
 
                                while (buffer.remaining() 0) {  
                                    byte b = buffer.get();  
                                    msg += (char) b;  
                                      
                                }  
 
                                buffer.clear();  
                            } else {  
                                client.close();  
                                break _FOR;  
                            }  
                        }  
                    }  
                }  
                double last = (System.currentTimeMillis() - start) * 1.0 / 1000;  
                System.out.println(msg + "used time :" + last + "s.");  
                msg = "";  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
 
    public static void main(String[] args) throws IOException {  
      
        String names[] = new String[SIZE];  
 
        for (int index = 0; index SIZE; index++) {  
            names[index] = "jeff[" + index + "]";  
            new Thread(new Message(names[index])).start();  
        }  
      
    }  

版权声明
本文来源于网络,版权归原作者所有,其内容与观点不代表牛牛娱乐立场。转载文章仅为传播更有价值的信息,如采编人员采编有误或者版权原因,请与我们联系,我们核实后立即修改或删除。

猜您喜欢的文章