NIO的簡單使用

目的是啓動一個服務端等待客戶端鏈接,鏈接成功後,客戶端發送字符串,服務端接收後展現。
服務端:java

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<SelectionKey> selectionKeys = selector.selectedKeys(); //獲取到有鏈接事件發生的channel的selectionKeys集合

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

    }
}
相關文章
相關標籤/搜索