NIOの簡単な使用

3130 ワード

目的は、クライアント接続を待つサービス側を起動し、接続に成功した後、クライアントは文字列を送信し、サービス側が受信した後に示すことです.サービス:
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;
import java.util.Set;

public class NIOServer {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        Selector selector = Selector.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); //ServerSocketChannel   Selector,       
        while(true){

            if(selector.select(1000) == 0){
                //  1s      ,     ,       
                System.out.println("     1s,   ");
                continue;
            }

            Set selectionKeys = selector.selectedKeys(); //           channel selectionKeys  

            Iterator iterator = selectionKeys.iterator();
            while (iterator.hasNext()){

                SelectionKey key = iterator.next();

                if(key.isAcceptable()){
                    //    
                    SocketChannel socketChannel = serverSocketChannel.accept(); //accept()    
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                    System.out.println("       ,    socketchannel:" + socketChannel.hashCode());
                }

                if(key.isReadable()){
                    //   
                    SocketChannel socketChannel = (SocketChannel) key.channel();
                    ByteBuffer byteBuffer = (ByteBuffer) key.attachment();
                    socketChannel.read(byteBuffer);
                    System.out.println("form     :" + new String(byteBuffer.array()));
                }
                iterator.remove();
            }

        }
    }
}
クライアント:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class NIOClient {
    public static void main(String[] args) throws IOException {

        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);

        if(!socketChannel.connect(inetSocketAddress)){
            while (!socketChannel.finishConnect()){
                System.out.println("      ,       ,       ");
            }
        }

        //    
        String str = "hello NIOServer";

        ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes());

        socketChannel.write(byteBuffer);

        System.in.read();

    }
}