JAva NIOインスタンス

11988 ワード

import java.io.IOException;  
import java.net.InetSocketAddress;  
import java.nio.ByteBuffer;  
import java.nio.channels.SelectionKey;  
import java.nio.channels.Selector;  
import java.nio.channels.SocketChannel;  
import java.util.Iterator;  

/** * NIO    * @author    */  
public class NIOClient {  
    //      
    private Selector selector;  

    /** *     Socket  ,               * @param ip        ip * @param port            * @throws IOException */  
    public void initClient(String ip,int port) throws IOException {  
        //     Socket   
        SocketChannel channel = SocketChannel.open();  
        //          
        channel.configureBlocking(false);  
        //           
        this.selector = Selector.open();  

        //         ,             ,   listen()     
        // channel.finishConnect();       
        channel.connect(new InetSocketAddress(ip,port));  
        //            ,       SelectionKey.OP_CONNECT  。 
        channel.register(selector, SelectionKey.OP_CONNECT);  
    }  

    /** *          selector           ,   ,      * @throws IOException */  
    @SuppressWarnings("unchecked")  
    public void listen() throws IOException {  
        //     selector 
        while (true) {  
            selector.select();  
            //   selector          
            Iterator ite = this.selector.selectedKeys().iterator();  
            while (ite.hasNext()) {  
                SelectionKey key = (SelectionKey) ite.next();  
                //      key,       
                ite.remove();  
                //        
                if (key.isConnectable()) {  
                    SocketChannel channel = (SocketChannel) key  
                            .channel();  
                    //       ,      
                    if(channel.isConnectionPending()){  
                        channel.finishConnect();  

                    }  
                    //        
                    channel.configureBlocking(false);  

                    //               
                    channel.write(ByteBuffer.wrap(new String("           ").getBytes()));  
                    //           ,             ,           。 
                    channel.register(this.selector, SelectionKey.OP_READ);  

                    //          
                } else if (key.isReadable()) {  
                        read(key);  
                }  

            }  

        }  
    }  
    /** *                  * @param key * @throws IOException */  
    public void read(SelectionKey key) throws IOException{  
        //     read     
    }  


    /** *         * @throws IOException */  
    public static void main(String[] args) throws IOException {  
        NIOClient client = new NIOClient();  
        client.initClient("localhost",8000);  
        client.listen();  
    }  

}  
import java.io.IOException;  
import java.net.InetSocketAddress;  
import java.nio.ByteBuffer;  
import java.nio.channels.SelectionKey;  
import java.nio.channels.Selector;  
import java.nio.channels.ServerSocketChannel;  
import java.nio.channels.SocketChannel;  
import java.util.Iterator;  

/** * NIO    * @author    */  
public class NIOServer {  
    //      
    private Selector selector;  

    /** *     ServerSocket  ,               * @param port        * @throws IOException */  
    public void initServer(int port) throws IOException {  
        //     ServerSocket   
        ServerSocketChannel serverChannel = ServerSocketChannel.open();  
        //          
        serverChannel.configureBlocking(false);  
        //        ServerSocket   port   
        serverChannel.socket().bind(new InetSocketAddress(port));  
        //           
        this.selector = Selector.open();  
        //            ,       SelectionKey.OP_ACCEPT  ,      , 
        //       ,selector.select()   ,        selector.select()     。 
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);  
    }  

    /** *          selector           ,   ,      * @throws IOException */  
    @SuppressWarnings("unchecked")  
    public void listen() throws IOException {  
        System.out.println("       !");  
        //     selector 
        while (true) {  
            //         ,    ;  ,         
            selector.select();  
            //   selector         ,           
            Iterator ite = this.selector.selectedKeys().iterator();  
            while (ite.hasNext()) {  
                SelectionKey key = (SelectionKey) ite.next();  
                //      key,       
                ite.remove();  
                //           
                if (key.isAcceptable()) {  
                    ServerSocketChannel server = (ServerSocketChannel) key  
                            .channel();  
                    //             
                    SocketChannel channel = server.accept();  
                    //        
                    channel.configureBlocking(false);  

                    //               
                    channel.write(ByteBuffer.wrap(new String("           ").getBytes()));  
                    //           ,             ,           。 
                    channel.register(this.selector, SelectionKey.OP_READ);  

                    //          
                } else if (key.isReadable()) {  
                        read(key);  
                }  

            }  

        }  
    }  
    /** *                  * @param key * @throws IOException */  
    public void read(SelectionKey key) throws IOException{  
        //         :       Socket   
        SocketChannel channel = (SocketChannel) key.channel();  
        //          
        ByteBuffer buffer = ByteBuffer.allocate(10);  
        channel.read(buffer);  
        byte[] data = buffer.array();  
        String msg = new String(data).trim();  
        System.out.println("       :"+msg);  
        ByteBuffer outBuffer = ByteBuffer.wrap(msg.getBytes());  
        channel.write(outBuffer);//           
    }  

    /** *         * @throws IOException */  
    public static void main(String[] args) throws IOException {  
        NIOServer server = new NIOServer();  
        server.initServer(8000);  
        server.listen();  
    }  

}