NIO实现的客户端与通信端范例

public class NIOServer {

private static int BUFF_SIZE=1024;
private static int TIME_OUT = 2000;

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

    Selector selector = Selector.open();
    ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
    serverSocketChannel.bind(new InetSocketAddress(10083));
    serverSocketChannel.configureBlocking(false);
    serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
    TCPProtocol protocol = new EchoSelectorProtocol(BUFF_SIZE);
    while (true) {
        if(selector.select(TIME_OUT)==0){
            //在等待信道准备的同时,也可以异步地执行其他任务,  这里打印*
            System.out.print("*");
            continue;
        }
        Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();
        while (keyIter.hasNext()) {
            SelectionKey key = keyIter.next();
            //如果服务端信道感兴趣的I/O操作为accept
            if (key.isAcceptable()){
                protocol.handleAccept(key);
            }
            //如果客户端信道感兴趣的I/O操作为read
            if (key.isReadable()){
                protocol.handleRead(key);
            }
            //如果该键值有效,并且其对应的客户端信道感兴趣的I/O操作为write
            if (key.isValid() && key.isWritable()) {
                protocol.handleWrite(key);
            }
            //这里需要手动从键集中移除当前的key
            keyIter.remove();
        }

    }
}

}
复制代码

复制代码
public class NIOClient {

public static Selector selector;
public static SocketChannel clntChan;

static {
    try {
        selector = Selector.open();
        clntChan = SocketChannel.open();
        clntChan.configureBlocking(false);
        clntChan.connect(new InetSocketAddress("localhost", 10083));
        clntChan.register(selector, SelectionKey.OP_READ);
        while (!clntChan.finishConnect()){

        }
        System.out.println("已连接!");
    }catch (Exception e){
        e.printStackTrace();
    }
}

public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = NIOClient.clntChan;
        ByteBuffer byteBuffer = ByteBuffer.allocate(256);
        new Avca(selector,socketChannel).start();
        while (true){
            Scanner scanner = new Scanner(System.in);
            String word = scanner.nextLine();
            byteBuffer.put(word.getBytes());
            byteBuffer.flip();
            socketChannel.write(byteBuffer);
            byteBuffer.clear();
        }
}

static class Avca extends Thread{
    private Selector selector;
    private SocketChannel clntChan;

   public Avca(Selector selector,SocketChannel clntChan){
        this.selector = selector;
        this.clntChan = clntChan;
   }

    @Override
    public void run(){
        try {
            while (true){
                selector.select();
                Set<SelectionKey> keys = selector.selectedKeys();
                Iterator<SelectionKey> keyIterator = keys.iterator();
                ByteBuffer byteBuffer = ByteBuffer.allocate(256);
                while (keyIterator.hasNext()){
                    SelectionKey selectionKey = keyIterator.next();
                    if (selectionKey.isValid()){
                        if (selectionKey.isReadable()){
                            SocketChannel socketChannel = (SocketChannel)selectionKey.channel();
                            socketChannel.read(byteBuffer);
                            byteBuffer.flip();
                            byte[] bytes = new byte[byteBuffer.remaining()];
                            byteBuffer.get(bytes);
                            System.out.println(new String(bytes));
                            byteBuffer.clear();
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值