NIO的简单使用

目的是启动一个服务端等待客户端连接,连接成功后,客户端发送字符串,服务端接收后展示。
服务端:

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();

    }
}

你可能感兴趣的:(java,nio)